Ssank
Ssank

Reputation: 3677

Using sed selectively to delete lines

I have a text file (say file)

Name
aaa
bbb
ccc
Name
xxxx
Name
yyyy
tttt

I want to remove "Name" from the file except if it occurs in the header. I know sed removes lines, but if I do

sed '/Name/d' file

it removes all "Name".

Desired ouput:

Name
aaa
bbb
ccc
xxxx
yyyy
tttt

Can you suggest what options I should use?

Upvotes: 2

Views: 95

Answers (3)

Ed Morton
Ed Morton

Reputation: 204558

You might find the awk syntax more intuitive:

awk 'NR==1 || !/Name/' file

the above just says if it's line number 1 or the line doesn't include "Name" then print it

Upvotes: 2

Thor
Thor

Reputation: 47219

If you know that the first header is on the first line, skip it like this:

sed '1!{/Name/d}' infile

That means the pattern should apply on all lines except line 1.

Or the other way around:

sed -n '2,${/Name/d};p' infile

Perhaps with awk:

 awk '/Name/ && c++ == 0 || !/Name/' infile

Output in all cases:

Name
aaa
bbb
ccc
xxxx
yyyy
tttt

Upvotes: 2

hek2mgl
hek2mgl

Reputation: 158230

Use this:

sed '1!{/Name/d}' file

The previous command applies to all lines except of the first line.

Upvotes: 2

Related Questions