Search code examples
stringlanguage-agnostic

Want to match a string exactly, despite variants, and remove only that string


I have the need to remove a specific, exact string from a file. This is being utilized as part of a clean-up process that I'm implementing. The problem is, there are variants that are similar to, but not exactly the same as the specially exact string that I want to remove.

For example, here is a sample of the file "sample":

tmp2
tmp3
tmp0
tmp1
tmp3
tmp3
tmp3
tmp1.1
tmp3
tmp2
tmp3
tmp1.2
tmp4

I want to remove only "tmp1", not "tmp1.1" or "tmp1.2".

I am using a single-lined Perl command:

perl -i -nle 'print if !/tmp1/' ./sample

Obviously, the single-lined script isn't cutting. Sure, it's removing "tmp1", but, it's Aalso removing "tmp1.1" and "tmp1.2" as well.

Any ideas?


Solution

  • Use anchors. ^ for beginning of line, and $ for end of line.

    $ perl -i -nle 'print if !/^tmp1$/' ./sample