change/substitute two different pattern in only one line

72 Views Asked by At

i try to change two different pattern in one line from a file.

the file is a /etc/fstab like :

/dev/sda1        /               ext4    auto,acl,errors=remount-ro  0       1
/dev/sda2        /home           ext4    auto,acl,errors=remount-ro  0       2

the result must be :

/dev/sda1        /               ext4    auto,acl,errors=remount-ro  0       1
/dev/mapper/home /home           ext4    auto,acl,errors=remount-ro  0       0

what i do on the first pattern:

sed -i "s/sda2/mapper\/home/" /etc/fstab

for the second pattern i have tried :

sed -i "s/sda2/mapper\/home/;s/[0-9]$/0/" /etc/fstab

but it update all lines :

/dev/sda1        /               ext4    auto,acl,errors=remount-ro  0       0
/dev/mapper/home /home           ext4    auto,acl,errors=remount-ro  0       0

Anyone can help me ? Thanks a lot !

2

There are 2 best solutions below

0
On BEST ANSWER

You can use the syntax address function-list to apply a set of commands to lines that match a pattern:

sed -i "/sda2/{ s/sda2/mapper\/home/
                s/[0-9]$/0/ }" /etc/fstab
0
On

You can use awk:

awk '$1 ~ /sda2/{sub(/sda2/, "mapper/home", $1); $NF=0} 1' file | column -t
/dev/sda1         /      ext4  auto,acl,errors=remount-ro  0  1
/dev/mapper/home  /home  ext4  auto,acl,errors=remount-ro  0  0

Use of column -t is for formatting only.