Reputation: 339
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 bravo
s, like:
bravo|october
bravo|romeo
Upvotes: 0
Views: 153
Reputation: 10039
2 way (at least) with sed
removing unwanted line
sed '/^bravo\|/ !d' YourFile
Printing only wanted lines
sed -n '/^bravo\|/ p' YourFile
d
cycle directly to the next line and a p
will print then continue the following action.
Upvotes: 1
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
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