2010-07-28 4 views
1

sed를 사용하여 한 줄에 몇 개의 일치 항목을 바꾸는 방법은 무엇입니까?sed를 사용하여 한 줄에 몇 개의 일치 항목을 바꾸는 방법

나는 텍스트로 file.log 있습니다

 
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/somepath_abc123/somepath3/file2.o;/somepath1/somepath_abc123/somepath3/file2.cpp; 

을 그리고 각 줄에 somepath1/somepath_abc123/somepath3을 대체하기 위해 노력하고있어.

그러나 가능성이 결과는 잘못된 것입니다 :

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

당신은 나오지도 수익을 볼 수있는 마지막 일치합니다. 표현과

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

무슨 잘못 :

나는 다음 코드를 시도?

+0

그건 sed 정규 표현식이 욕심 때문입니다. – ghostdog74

답변

1
#!/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 

출력

$ ./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

고맙습니다. ghostdog74. 그것은 잘 작동합니다. 하지만 현재 작업에 sed를 사용해야합니다. – pathsag

3

[^ /] 대신 사용해보십시오.

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

:

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

그렇지 않으면, 나오지도 같은 호출을 지원 펄에 나오지도 교체합니다. ? 와 같다 .하지만 욕심이 없습니다.

+0

마르코 감사합니다! 대신 [^ /] 바꾸기. 완벽하게 작동합니다. 이제 출력을 기대합니다. – pathsag

관련 문제