Sed: replacing entries in the /etc/fstab

awkfstabregular expressionsedtext processing

I'm in the process of hardening some of our systems. As part of that hardening process, I need to update a few entries in the /etc/fstab to limit the capabilities of some of the various partitions.

With that said, I would like be able to use a sed in-line replace to update the rows. Below is a snippet from the current /etc/fstab:

# /etc/fstab
# Created by anaconda on Wed Feb 21 09:37:23 2018
/dev/mapper/vg1-lv_root /                       ext4    defaults        1 1
/dev/mapper/vg1-lv_home /home                   ext4    defaults        1 2
tmpfs                   /dev/shm                tmpfs   defaults        0 0

After the sed command is run I would like the file to look like the following:

# /etc/fstab
# Created by anaconda on Wed Feb 21 09:37:23 2018
/dev/mapper/vg1-lv_root /                       ext4    defaults        1 1
/dev/mapper/vg1-lv_home /home                   ext4    defaults,nodev        1 2
tmpfs                   /dev/shm                tmpfs   defaults        0 0

Basically, I need to add "nodev" to all the rows that are ext[2-4], that aren't the root partition.

The sed command that I put together comes close to doing this, but for whatever reason, I can't get the regex to not match the "/" partition, so it always updates that row also.

sed '/^[^#].*ext[2-4]/s/defaults/defaults,nodev/g' /etc/fstab

I would like to key off of the "/" surrounded by spaces, not the vg1-lv_root. The following works, but I don't like the solution because it's clunky:

sed '/^[^#].*ext[2-4]/s/defaults/defaults,nodev/g' /etc/fstab | sed '/^[^#].*root.*ext[2-4]/s/defaults,nodev/defaults/' > /etc/fstab

Best Answer

You could use awk to add the logic to add the string and column to reformat the final output file. Assuming you have write permissions to the /etc/ and /tmp/ folders

tempfile=$(mktemp /tmp/tmpfile.XXXXXXXX)

This would create the temporary file in the /tmp/ path in which you can write the awk output to and re-direct that back to the original file

awk '$3 ~ "ext[2-4]"{ $4=$4",nodev" }1 ' /etc/fstab | column -t > "$tempfile" && mv -- "$tempfile" /etc/fstab

The column -t part is just redundant and needed to look the output file more readable, rather to make it disordered and clunky.

Related Question