user3614491
user3614491

Reputation: 15

Perl:Match a string and delete all but first occurrence

I have a file in perl that has the following content

abc
text1 
text2
text3
abc
text4
text5
abc
abc

Final output:

abc
text1
text2
text3
text4
text5

I want to use a perl one liner or a script to retain the 1st abc and delete the rest. In my script I am using pattern matching operator m?/abc/ to find the 1st pattern but not able to figure out a way to delete the rest. Please help me with the same

Upvotes: 0

Views: 745

Answers (1)

j_random_hacker
j_random_hacker

Reputation: 51226

Assuming you want to delete the entire line containing the second and subsequent occurrences of abc:

perl -ne 'print if !/abc/ || !$n++' < infile > outfile

If you want to delete lines containing abc and nothing else, change /abc/ to /^abc$/.

Upvotes: 3

Related Questions