Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally remove first line only with sed when it matches?

Tags:

sed

Can I use sed to check the first line of some command's output (to stdout) and delete this very first line if it matches a certain pattern?

Say, the command's output is something like this:

"AB"
"CD"
"E"
"F"

I want it to become:

"CD"
"E"
"F"

But when the first line is "GH", I don't want to delete the line.

I tried this, but it doesn't work:

<some_command> |sed '1/<pattern>/d'

The shell told me:

sed: 0602-403 1/<pattern>/d is not a recognized function.

I only want to use sed to process the first line, leaving the other lines untouched.

What is the correct syntax here?

like image 923
Qiang Xu Avatar asked Apr 20 '13 23:04

Qiang Xu


People also ask

What is P option in sed?

In sed, p prints the addressed line(s), while P prints only the first part (up to a newline character \n ) of the addressed line. If you have only one line in the buffer, p and P are the same thing, but logically p should be used.

What is G option in sed?

Substitution command In some versions of sed, the expression must be preceded by -e to indicate that an expression follows. The s stands for substitute, while the g stands for global, which means that all matching occurrences in the line would be replaced.

How do I remove a number from sed?

You need to use regular expression to remove digits or number from input. For example, 's/[0-9]*//g' will remove all numbers from the input.


2 Answers

This might work for you:

sed -e '1!b' -e '/GH/!d' file
like image 193
potong Avatar answered Nov 17 '22 20:11

potong


You want to reference the 1st line, then say delete:

$ sed '1 d' file

No need for any pattern if you know which line you want to delete.

With a pattern, use this syntax:

$ sed '0,/pattern/ d' file
like image 29
Alexis Wilke Avatar answered Nov 17 '22 20:11

Alexis Wilke