Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading