Aminator
Aminator

Reputation: 160

sed command that combine two command that are dependant on each other

I need help with a sed command that copies the line of birthday to standard output, removing all lines that start with an "A". Suppose my sample.txt file looks like this:

A birthday is very much celebrated. 
Today is my birthday.
I can celebrate my birthday. 
A man can do anything.

and this is the sample output:

Today is my birthday.
I can celebrate my birthday.

So, for the birthday line:

sed -n /birthday/p sample.txt

and for the removing the lines that starts with "A":

sed -n '/^A/!p' sample.txt

Now, i am confused on how to combine these two lines so that they can work according to the question.

Upvotes: 2

Views: 165

Answers (3)

potong
potong

Reputation: 58430

This might work for you (GNU sed):

sed '/^A/d;/birthday/!d' file

If a line begins with A delete it and delete any other lines that do not have birthday.

Or:

sed -n '/^[^A].*birthday/p' file

Print lines that don't begin with an A and contain birthday.

Upvotes: 1

user14424105
user14424105

Reputation:

Using sed, no pipe is required - you can delete lines which begin with "A" before printing those which contain "birthday":

sed -n '/^A/d; /birthday/p' file

Or use sed's default print action (by not disabling it via the -n option): delete lines which do not contain "birthday". Any lines which do not get deleted will be printed to the standard output.

sed '/^A/d; /birthday/!d' file

Using this method, the order of the addresses could be swapped without affecting the logic: /birthday/!d; /^A/d produces the same output.

Upvotes: 1

j4ckofalltrades
j4ckofalltrades

Reputation: 610

What you want is the pipe operator |. It takes the output of the command one the left and 'pipes' it to the command on the right by connecting STDOUT to STDIN.

So in your case you'd do:

sed -n /birthday/p sample.txt | sed -n '/^A/!p'

Edit: formatting

Upvotes: 1

Related Questions