0

I have the following text file contents:

/fubar/bob

/fubar/harry

/fubar/harry-

/fubar/steve

/fubar/tim

/fubar/tim-

/fubar/atim

/fubar/atim-

/fubar/jane

I am using sed to remove all lines containing references to harry, tim and atim.

sed -i 's#/fubar/\(harry\|tim\|atim\)\(\-\?\)##' /input/testfile.txt

This gives me the following output:

/fubar/bob

.

.

/fubar/steve

.

.

.

.

/fubar/jane

Where the . doesn't actually exist, just using them to represent blank space in the file structure. Is there a way to adjust the sed statement so that it will remove the blank space in one line or will I need a second sed statement to do this? I can't seem to find anything online that combines the blank space removal with another function.

Community
  • 1
  • 1
Mike
  • 618
  • 2
  • 8
  • 27

2 Answers2

2

Use can use d (delete) option in sed:

sed -E '\#/fubar/(harry|tim|atim)#d' file

/fubar/bob
/fubar/steve
/fubar/jane

To save changes back to file use:

sed -i.bak -E '\#/fubar/(harry|tim|atim)#d' file
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • [Here is a working demo](https://ideone.com/j89vka) of above `sed` command. – anubhava Nov 29 '17 at 11:16
  • 1
    Will accept this once I can. Didn't work initially due to user error. Can I ask what the first \ does? – Mike Nov 29 '17 at 11:17
  • 1
    FIrst backslash is used for escaping an alternative delimiter which is `#` in this case.Otherwise we can use `sed -E '/\/fubar\/(harry|tim|atim)/d' file` also. – anubhava Nov 29 '17 at 11:18
  • 1
    @Mike see also https://stackoverflow.com/questions/5864146/use-slashes-in-sed-replace/5864155#5864155 – Sundeep Nov 29 '17 at 11:23
0

The more robust awk solution:

awk -F'/' 'NF && $NF!~/(harry|tim|atim)-?/' file > tmp_f && mv tmp_f file

The final file contents:

/fubar/bob
/fubar/steve
/fubar/jane
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105