开发者

Using sed to replace matches of a string

开发者 https://www.devze.com 2023-04-11 18:41 出处:网络
I have various java files that have the following statement in their methods: var1.setMaximumSize((-1));

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 (e.g. 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'


If your sed implementation supports the -i (in-place) option:

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
0

精彩评论

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

关注公众号