开发者

How to replace a few matches in one line using sed

How to replace a few matches in one line using sed?

I have a file.log with text:

sometext1;/somepath1/somepath_abc123/somepath3/file1.a;/somepath1/somepath_abc123/somepath3/file1.o;/somepath1/somepath_abc123/somepath3/file1.cpp;
sometext2;/somepath1/somepath_abc123/somepath3/file2.a;/somepath/so开发者_JAVA技巧mepath_abc123/somepath3/file2.o;/somepath1/somepath_abc123/somepath3/file2.cpp;

And I'm trying to replace somepath1/somepath_abc123/somepath3 in each line.

But unlikely the results is wrong:

sometext1;/mysomepath1/mysomepath2/mysomepath3/file1.cpp;
sometext2;/mysomepath1/mysomepath2/mysomepath3/file2.cpp;

As you can see the sed returns only the last match.

I tried the following code:

#!/bin/sh
FILE="file.log"
OLD="somepath1\/somepath_.*\/somepath3"
NEW="mysomepath1\/mysomepath2\/mysomepath3"
sed  's|'"$OLD"'|'"$NEW"'|g' $FILE > $FILE.out

Whats wrong with the expression?


Try using [^/] instead of .

#!/bin/sh
FILE="file.log"
OLD="somepath1/somepath_[^/]*/somepath3"
NEW="mysomepath1/mysomepath2/mysomepath3"
sed  "s|$OLD|$NEW|g" $FILE > $FILE.out

Otherwise, replace sed with perl which supports a sed-like invocation:

#!/bin/sh
FILE="file.log"
OLD="somepath1/somepath_.*?/somepath3"
NEW="mysomepath1/mysomepath2/mysomepath3"
perl -pe "s|$OLD|$NEW|g" $FILE > $FILE.out

where .? is the same as . but it is non greedy.


#!/bin/bash

awk -F";" '
{
  for(i=1;i<=NF;i++){
    if($i ~ /somepath1.*somepath3/ ){
      sub(/somepath1\/somepath_.*\/somepath3/,"mysomepath1/mysomepath2/mysomepath3",$i)
    }
  }
}
1' OFS=";" file

output

$ ./shell.sh
sometext1;/mysomepath1/mysomepath2/mysomepath3/file1.a;/mysomepath1/mysomepath2/mysomepath3/file1.o;/mysomepath1/mysomepath2/mysomepath3/file1.cpp;
sometext2;/mysomepath1/mysomepath2/mysomepath3/file2.a;/somepath/somepath_abc123/somepath3/file2.o;/mysomepath1/mysomepath2/mysomepath3/file2.cpp;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜