Home > Software design >  Trying to replace certain words in the lines of a file with sed
Trying to replace certain words in the lines of a file with sed

Time:09-01

I have the following text file in Linux, named "matricole.testo" :

paolo rossi 1988
giovanna d'arco 1945
francesco totti 1988
francesco gabbani 1967
andrea presti 1957
franco taoli 1945
giuseppe verdi 1987

My goal is to replace, in the first 7 lines of the file, all the words (not the whole lines) which ends with '88' with a blank space, so the result would be the following (I think) :

paolo rossi 
giovanna d'arco 1945
francesco totti 
francesco gabbani 1967
andrea presti 1957
franco taoli 1945
giuseppe verdi 1987

To reach this result I tried the command sed -e '1,7 s/\<.*88\>//g', but it replaces the whole lines with a blank space; how can I change just the words as expected ?

Please note that I should use the sed command exclusively.

CodePudding user response:

Only delete the part you want to delete.

sed -e '1,7s/[0-9]*88$//' file

The /g flag only makes sense when you expect multiple matches per line, which by definition you cannot expect when you anchor the search to the end of line. There is only one end on each line. (The other end is called the "beginning" and is matched by ^ instead.)

Replacing the match with a space could be added, but the way it's defined now, it will leave the space just before the final number sequence.

In case it's not obvious, the "match anything" wildcard .* matches the longest leftmost possible string. If you don't want that, you have to constrain what you put before the * repeat operator one way or another.

If you want to replace all words which end with 88 and your sed dialect understands \> to mean the word boundary to the right of a word, try

sed -e '1,7s/[^ ]*88\>//g' file
  • Related