简体   繁体   中英

Using sed to replace matches of a string

I have various java files that have the following statement in their methods:

      var1.setMaximumSize((-1));

The statement starts with 6 white spaces.

I am trying to delete these lines or replace them with an empty string. I have tried the following script with no success:

for fl in *.java; do
    mv $fl $fl.old
    sed 's/^\s*var[0-9]+\.setMaximumSize\(\(-1\)\);$//g' $fl.old > $fl
    rm -f $fl.old
done

I think it doesn't work because you are using extended regexes (eg the + quantifier), so you have to use sed -r .

You may also perform an in-place edit, from man sed :

  -i[SUFFIX], --in-place[=SUFFIX] edit files in place (makes backup if extension supplied) 

So this should work:

sed -r -i'' -e's/^\s*var[0-9]+\.setMaximumSize\(\(-1\)\);$//g' *.java

Many implementations of sed do not accept modern regex patterns. The ones that might be problematic in your expression are \\s and +. (Try \\+). Also, sed treats ( as a normal character which must be escaped to become a meta character. You could try:

$ sed '/^      var[0-9][0-9]*.setMaximumSize((-1));$/d'

如果您的sed实现支持-i(就地)选项:

sed  -i '/^ \{6\}var[0-9][0-9]*.setMaximumSize((-1));$/d' *java

If you want to use literal parentheses, you don't need to escape it. sed interprets escaped parentheses as a grouping. Also, you need to escape the '+' to use it correctly:

sed 's/^\s*var[0-9]\+\.setMaximumSize((-1));$//g' $fl.old > $fl

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM