3

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:

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

output:

ABC1234 
Kusalananda
  • 333,661

1 Answers1

3

With

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
Kusalananda
  • 333,661
  • 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
  • @Kusalananda could you provide the perl one liner for the same to insert the text on the same file – satsensort Feb 26 '19 at 16:16