开发者

How can I get regex/sed to recognize the line the search string is on?

开发者 https://www.devze.com 2023-02-11 10:42 出处:网络
I\'m brand new to regex. I am trying to write a script to comment out lines in a file, so that when we retire a network computer we can remove it from our administrative files (rdist, etc) witho开发者

I'm brand new to regex. I am trying to write a script to comment out lines in a file, so that when we retire a network computer we can remove it from our administrative files (rdist, etc) witho开发者_StackOverflow中文版ut having to comment them out by hand. What I have so far is

#!/bin/bash

echo $*                      
NAMES=$*                    
FILES="/foo/testfile1        
/foo/testfile2"

for name in $NAMES
        do               
        sed -i "s/${name}/#&/g" $FILES
done
exit 0

This works when the testfiles have the target string appear at the beginning of the line, but not if the string is somewhere in the middle. How can I tell sed or regex to insert a hash at the beginning of the line that the string is found on?

(I've been reading my way through a bunch of tutorials online, but the closest thing to what I want seems to be the carat ^. What I'm getting from the explanation is that in multiline mode, it only returns instances of the string that are located at the beginning of the line.)

I'm working on RedHat 5.5, using gedit 2.8.1 as my text editor and sed 4.1.2.

Thank you in advance for your help!


The script below will take in the passed in arguments and look for them as whole words. i.e if an argument is foo then blah foo bar will be commented out but blahfoo bar will not. I also added a bit of code so that if a line matches multiple arguments, you will still only get one # at the beginning of the line.

#!/bin/bash

FILES="./test1 ./test2"

for name; do
  sed -i "/\<$name\>/s/^#*/#/" $FILES
done


Stealing the structure from SiegeX and simplifying the sed program:

#!/bin/bash

FILES="./test1 ./test2"

for name; do
  sed -i "s/^.*$name.*$/#&/" $FILES
done

The idea is that rather than using a pattern to select and then an s to edit, you use the s pattern to do both - recognise a complete line that contains the target name, and replace it with a commented-out version.

You could do this more elegantly by merging the names into one big regular expression; that would let sed make one pass rather than N. That's easy enough that i leave it as an exercise to the reader ...

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号