Username
Username

Reputation: 3663

How do I delete every line from a file matching the first line

I want to delete every line of a file that matches the first line, but not delete the first line.

I've tried this code so far, but it deletes all matching patterns including the first line.

sed -i "1,/$VARIABLE_CONTAINING_PATTERN/d" $MY_FILE.txt

Upvotes: 1

Views: 60

Answers (3)

potong
potong

Reputation: 58401

This might work for you (GNU sed):

sed -i '1h;1!G;/^\(.*\)\n\1$/!P;d' file

Copy the first line into the hold space (HS). For every line except the first, append the HS to the pattern space (PS). Compare the current line to the first line and print the current line if it is not the same. Delete the pattern space.

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Following your description literally - to delete every line of a file that matches the first line, but not delete the first line, awk solution:

Let's say we have the following myfile.txt:

my pattern
some text
another pattern
regex
awk sed
my pattern
text text
my pattern
our patterns

awk 'NR==1{ pat=$0; print }NR>1 && $0!~pat' myfile.txt > tmp && mv tmp myfile.txt

Final myfile.txt contents:

my pattern
some text
another pattern
regex
awk sed
text text
our patterns

Upvotes: 2

James Brown
James Brown

Reputation: 37404

Using awk. Solution depends a bit on your definition of a match:

$ cat file
1
2
3
1
12
$ awk 'NR==1{p=$0;print;next} p $0 != p' file
1
2
3
12
$ awk 'NR==1{p=$0;print;next} $0 !~ p' file
1
2
3

Therefore you should provide proper sample data with the expected output.

Upvotes: 0

Related Questions