0

How can I keep all lines matching all those words toto OR titi OR clic OR SOMETHING and delete any other lines?

If I do sed '/toto/ p ' file I cannot select titi for example.

What I am looking for is something similar to a Perl Regular expression as ^ (word1|word2|word3|andsoon).*. However, I need it for sed because it will be integrated into a bigger sed script.

The goal is to keep all lines starting with word where word is any word from a set of words.

kvantour
  • 25,269
  • 4
  • 47
  • 72
francois P
  • 306
  • 6
  • 20
  • How is your larger `sed` script called? If it is called just as `sed`, then the task at hand would be to delete all lines that do not match to corresponding expressions, if it is called as `sed -n` you actually have to select the lines you are interested in. But my overall suggestion would be set your first `awk` rule to delete the lines that do not match. – kvantour Nov 23 '18 at 10:08

1 Answers1

1

The answer here depends a bit on how your master script is called. Imagine you have a file with the following content:

foo
car
bar

and you are interested in the lines matching "foo" and "bar", then you can do:

sed '/foo\|bar/!d'
sed -n '/foo\|bar/!d;p'
sed -n '/foo\|bar/p'

all these will output:

foo
bar

If you would just do:

sed '/foo\|bar/p'

you actually duplicate the lines.

foo
foo
car
bar
bar

As you see, there is a bit of different handling depending on the usage of the -n flag.

-n, --quiet, --silent suppress automatic printing of pattern space

source: man sed

In general, my suggestion is to delete the lines you don't need at the beginning of your sed script.

Community
  • 1
  • 1
kvantour
  • 25,269
  • 4
  • 47
  • 72