Home > Enterprise >  Use variables instead of values in sed commande to replace words in a text file
Use variables instead of values in sed commande to replace words in a text file

Time:01-03

I have to edit /etc/fstab to change mounting options for /dev/shm parameter.

source line is :

tmpfs                   /dev/shm                tmpfs   size=11g        0 0

I want to add noexec to the fourth field (mounting options) for the /dev/shm partition for many of servers.(with different size in mounting options) So I tiried this code: To obtain the value of mounting options. I used:

shmvar=`grep -E '\s/dev/shm\s' /etc/fstab | awk '{ print $4 }'`

the output is : size=11g

sed -i -e '/shm/s/$shmvar/$shmvar,noexec/' /etc/fstab

OR

sed -i -e '/shm/s/$shmvar/&,noexec/' /etc/fstab

but none of the sed commands worked.

while I use "size=11g" instead of "$shmvar" it works:

 sed -i -e '/shm/s/size=11g/size=11g,noexec/' /etc/fstab
OR
sed -i -e '/shm/s/size=11g/&,noexec/' /etc/fstab

But because the "size" value is different in servers, I have to use variables

Would highly appreciate some quick help. Thanks

CodePudding user response:

With GNU awk. If second field contains /dev/shm then append ,noexec to fourth field.

awk -i inplace 'BEGIN{ OFS="\t" } $2=="/dev/shm"{ $4=$4 ",noexec" } { print }' file

Output:

tmpfs   /dev/shm        tmpfs   size=11g,noexec 0       0
  • Related