Brian Kuepper
Brian Kuepper

Reputation: 11

using sed to edit /etc/fstab

/etc/fstab line I want to edit:

/dev/appvg/home         /home     ext3    defaults        0 0

How do I get sed to insert ",nodev" behind the defaults column?

I found this command in another post that inserts it before "defaults", and I can't figure out how get to insert after:

sed -ie 's:\(.*\)\(\s/home\s\s*\)\(\w*\s*\)\(\w*\s*\)\(.*\):\1\2\3nodev,\4\5:' /etc/fstab

which gives me this:

/dev/appvg/home         /home     ext3    nodev,defaults  0 0

This is how I want it to look like:

/dev/appvg/home         /home     ext3    defaults,nodev  0 0

Is it possible? I'm new to sed...

Upvotes: 1

Views: 10025

Answers (3)

Abu Shumon
Abu Shumon

Reputation: 1994

You can try this way also:

sed "s*/opt/apps/app1               ext4    defaults        1 1*/opt            ext4    defaults        1 2*g" -i /etc/fstab
  • from frist * to second *: string to be searched for
  • from second * to third *: string to be replaced with.

you can first try without -i option which outputs changes on terminal but doesn't actually change in the actual file.

Upvotes: 1

iamauser
iamauser

Reputation: 11489

You can also use awk. Generally in Linux, defaults comes in the 4th column of the /etc/fstab file. You could use that to print only if the line has a default in it.

awk '/defaults/{$4="defaults,nodev"}{print}' /etc/fstab

To be specific to your case,

awk '/\/dev\/appvg\/home/{$4="defaults,nodev"}{print}' /etc/fstab

Upvotes: 1

Paul Wagland
Paul Wagland

Reputation: 29149

The simplest answer to your question, assuming that this is exactly what you want to change is:

sed -ie '/^\/dev\/appvg\/home/ s/defaults/defaults,nodev/' /etc/fstab

What this says to do is to match the line starting (^) with ^/dev/appvg/home, and then apply the following command to it. In this case, the following command is "change defaults to defaults,nodev"

If you wanted to modify the command that you proposed to do the change, then you would want:

sed -ie 's:\(.*\)\s\(/home\)\s\s*\(\w*\)\s*\(\w*\)\s*\(.*\):\1 \2 \3 \4,nodev \5:' /etc/fstab

The \1, \2, etc between the last two ':' characters are replacement markers, and they say to replace the contents of the matching brackets from the first part of the expression. By changing where the \s are in the matching expression, then you only get the word (\w) characters and not the space (\s) characters in your substitution. Because of this, you need to insert your own spaces into the resulting string.

Upvotes: 5

Related Questions