HugMyster
HugMyster

Reputation: 339

Select specific items from a file using sed

I'm very much a junior when it comes to the sed command, and my Bruce Barnett guide sits right next to me, but one thing has been troubling me. With a file, can you filter it using sed to select only specific items? For example, in the following file:

    alpha|november
    bravo|october
    charlie|papa
    alpha|quebec
    bravo|romeo
    charlie|sahara

Would it be possible to set a command to return only the bravos, like:

    bravo|october
    bravo|romeo

Upvotes: 0

Views: 153

Answers (3)

NeronLeVelu
NeronLeVelu

Reputation: 10039

2 way (at least) with sed

removing unwanted line

sed '/^bravo\|/ !d' YourFile

Printing only wanted lines

sed -n '/^bravo\|/ p' YourFile
  • if no other constraint or action occur, both are the same and a grep is better.
  • If there will be some action after, it could change the performance where a d cycle directly to the next line and a p will print then continue the following action.
    • Note the escape of pipe is needed for GNU sed, not on posix version

Upvotes: 1

Wintermute
Wintermute

Reputation: 44023

With sed:

sed '/^bravo|/!d' filename

Alternatively, with grep (because it's sort of made for this stuff):

grep '^bravo|' filename

or with awk, which works nicely for tabular data,

awk -F '|' '$1 == "bravo"' filename

The first two use a regular expression, selecting those lines that match it. In ^bravo|, ^ matches the beginning of the line and bravo| the literal string bravo|, so this selects all lines that begin with bravo|.

The awk way splits the line across the field separator | and selects those lines whose first field is bravo.

You could also use a regex with awk:

awk '/^bravo|/' filename

...but I don't think this plays to awk's strengths in this case.

Upvotes: 3

Arjun Mathew Dan
Arjun Mathew Dan

Reputation: 5298

Another solution with sed:

sed -n '/^bravo|/p' filename

-n option => no printing by default. If line begins with bravo|, print it (p)

Upvotes: 2

Related Questions