1

Ubuntu, sed remove ze if ze is alone on the line

The closest I got is sed "s/\bze\b//g" and sed "s/^\bze\b//g" which does not produce the desired result.

Before sed:

ze.com
example.ze
zero.com
ze

After sed:

ze.com
example.ze
zero.com
0

2 Answers 2

5

You need line anchors rather than word boundaries

$ sed '/^ze$/d' file
ze.com
example.ze
zero.com
4

Using grep:

$ grep -vxF ze file
ze.com
example.ze
zero.com

The used options:

  • -v negates the sense of the match so that only lines not matching the pattern are returned.

  • -x requires that the pattern matches a complete line from start to finish.

  • -F tells grep that the pattern is a fixed string and not a regular expression.


The issue with your sed expressions is that a substitution modifies a line in the input, but it will never delete a line. The pattern \bze\b will correctly match the complete word ze, but that word exists on other lines too, not only on the last line.

To delete a line with sed, use its d command together with a regular expression that matches the line that you'd like to remove, such as ^ze$, as steeldriver shows in his answer.

For the specific example (removing the last line),

sed '$d' file

would also be an option. Here, $ is not a regular expression (since it's not within /.../) but the special address of the last line in the file.

Not the answer you're looking for? Browse other questions tagged .