sed command replaces all lines containing "name"

Viewed 36

I have a document with the next data:

SOMETHING_NAME=something
NAME=somethingmore

And when I run the next command:

sed -i "/NAME=/c NAME=newsomething" ./file

The command edit all matching with NAME, so I need to match only the second line.

file after:

NAME=newsomething
NAME=newsomething

The output I need:

SOMETHING_NAME=something
NAME=newsomething
3 Answers

You can just use this simple sed command using a capture group and start anchor:

sed -i.bak -E 's/^(NAME=).*/\1newsomething/' file

cat file

SOMETHING_NAME=something
NAME=newsomething

Breakup:

  • ^ Start a line
  • (NAME=): Match substring NAME= and capture in group #1
  • .*: Match rest of the line
  • \1newsomething: Replacement is \1 (back-reference of group #1) followed by newsomething

If you add a caret (^) to the regex that will match from the start of the line, as follow.

sed -i "/^NAME=/c NAME=newsomething" ./file

You can combine sed with \b to define word bountaries. I think bellow examples will help you better to understand the use of it and how you can use it in your case:

cat file1
name1 name2 name3
_name1 _name2 _name3

sed 's/\b_name1\b/XX/' file1
name1 name2 name3
XX _name2 _name3

sed 's/\bname1\b/XX/' file1
XX name2 name3
_name1 _name2 _name3

sed 's/\bname\b/XX/' file1
name1 name2 name3
_name1 _name2 _name3
# nothing is replaced since name is not a word/field in file1
Related