0

I have a file that looks like this called listofnames.txt.

this-is-name-1
this-is-name-2
...
this-is-name-11
this-is-name-12
this-is-name-13
this-is-name-14
...
this-is-name-21
....

I want to do a full match of a certain word and add a "0" next to it. I use the following command:

sed -i '/this-is-name-1/s/$/ 0/' ~/listofnames.txt

However, instead of this,

this-is-name-1 0
this-is-name-2
...
this-is-name-11
this-is-name-12
this-is-name-13
this-is-name-14
...
this-is-name-21
....

I get this,

this-is-name-1 0
this-is-name-2
...
this-is-name-11 0
this-is-name-12 0
this-is-name-13 0
this-is-name-14 0
...
this-is-name-21
....

What is wrong with my command? how do I fix it and do what I need. It seems to be doing a partial match instead of a full match.

anarchy
  • 759
  • 2
  • 13

2 Answers2

1

You just need to add start/end of string (line for sed by default) anchors:

sed 's/^this-is-name-1$/& 0/' file
Ed Morton
  • 157,421
  • 15
  • 62
  • 152
0

You have to match the word: this-is-name-1 so that to exclude cases like this-is-name-11 etc. There are many ways for doing this, depending the rest of your file content and what are the cases you want to protect your edit from. For example \b matches word bountaries, this includes white-space characters, the beginning/end of lines, and other non-alphanumeric characters. It seems good for your case:

sed -i '/\bthis-is-name-1\b/s/$/ 0/' file

You will find this read very useful: Reference - What does this regex mean?

thanasisp
  • 5,575
  • 3
  • 11
  • 27
  • 1
    do you think you could look at this, https://stackoverflow.com/questions/63865912/using-ssh-and-sed-within-a-python-script-with-os-system-properly the command works on its own but for some reason it doesn't work in this context – anarchy Sep 13 '20 at 00:02
  • use Python `subprocess` module, recommended in that good answer. – thanasisp Sep 13 '20 at 08:42