Im using perl to remove a string from a file, it is removing the string from file, But the actual line is not getting deleted, Due to which the next insert to the files are getting written over next line.

Perl command used:

perl -lpi -e "s/$host//g" /tmp/exclude_list


  • You are replacing a substring on each line in the file. Do you want to delete the whole line? – Kusalananda Feb 22 '19 at 9:51
  • @Kusalananda i want delete the whole line .. If you have options with awk also i can try. – satsensort Feb 22 '19 at 10:10
  • A already wrote an answer. – Kusalananda Feb 22 '19 at 10:12
  • grep -v is the simplest way to do it. – glenn jackman Feb 22 '19 at 14:47


cp /tmp/exclude_list /tmp/exclude_list.tmp
grep -Fx -v -e "$host" /tmp/exclude_list.tmp >/tmp/exclude_list
rm /tmp/exclude_list.tmp

you would remove each line that exactly matches the string in $host. Change -Fx to just -F to remove any line that contains the string. Don't use -F if you want to use $host as a regular expression.

Or with Perl:

perl -i -sn -e 'print unless /$host/' -- -host="$host" /tmp/exclude_list

The options used with perl here is -i for in-place editing, -s to allow Perl to instantiate the $host Perl variable from the command line, and -n to only print explicitly from within the implicit loop that Perl provides around the code. The -e takes the actual code as the argument.

The Perl code would remove all lines that does not match the regular expression $host.

To use $host as a string:

perl -i -sn -e 'print unless index($_, $host) >= 0' -- -host="$host" /tmp/exclude_list
| improve this answer | |
  • sed -i is not working on AIX Korn Shell. Thanks for the quick solution – satsensort Feb 22 '19 at 10:13
  • 1
    @kusalananda, sometimes "!..." expands for bash history. Perhaps "/host/ or print" – JJoao Feb 22 '19 at 12:32
  • 1
    @JJoao Thanks, I'm not on bash so I didn't think about that. (and the user is in ksh anyway) – Kusalananda Feb 22 '19 at 12:35
  • 1
    You can pass a shell variable into perl like this: perl -sne '/$host/ || print' -- -host="$host" /tmp/exclude_list -- that allows you to use single quotes around the perl script. -s enables something like awk's -v. You need -- to signal to perl that the command line options to the perl executable are finished, and the other options can be picked up by the script body. – glenn jackman Feb 22 '19 at 14:34
  • one last comment: if we're sure that $host is the only text on the line, then add the -l option (to auto strip/add newline) and print unless $_ eq $host – glenn jackman Feb 22 '19 at 14:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.