Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl one-liner: deleting a line with pattern matching

Tags:

perl

I am trying to delete bunch of lines in a file if they match with a particular pattern which is variable.

I am trying to delete a line which matches with abc12, abc13, etc.

I tried writing a C-shell script, and this is the code:

    **!/bin/csh
    foreach $x (12 13 14 15 16 17)
    perl -ni -e 'print unless /abc$x/' filename
    end**

This doesn't work, but when I use the one-liner without a variable (abc12), it works.

I am not sure if there is something wrong with the pattern matching or if there is something else I am missing.

like image 962
shiva1987 Avatar asked Nov 28 '15 17:11

shiva1987


1 Answers

Yes, it's the fact you're using single quotes. It means that $x is being interpreted literally.

Of course, you're also doing it very inefficiently, because you're processing each file multiple times.

If you're looking to remove lines abc12 to abc17 you can do this all in one go:

perl -n -i.bak -e 'print unless m/abc1[234567]/' filename
like image 63
Sobrique Avatar answered Nov 12 '22 17:11

Sobrique