Qiu Yangfan
Qiu Yangfan

Reputation: 891

How to remove line matching specific pattern from a file

  1. I know sed could be used to delete specific line from file:

    sed -i "/pattern/d" file
    
  2. While the pattern of my case includes slash, like /var/log,

    So I know I need escape: sed -i "/\/tmp\/dir/d" file

  3. However, for my case, the pattern is dynamic, should be a variable in a shell file, so I have to convert the variable value to replace "/" with "\\/", then got this:

     sed -i "/^${pattern_variable//\\//\\\\\\/}$/d" file
    

My question is, is there any better implementation which is more readable or simpler? Not only sed, other utility is also acceptable. Is it possible to handle not only slash but also other various symbols, like backslash or # ()?

Upvotes: 1

Views: 144

Answers (1)

Kent
Kent

Reputation: 195029

you can use char other than /:

sed "\#$varHasSlash#d"

example:

kent$  foo="b/c"

kent$  echo "a
ab/cd
e"|sed "\#$foo#d"
a
e

Upvotes: 1

Related Questions