2010-07-28 7 views
1

Comment remplacer quelques correspondances dans une ligne en utilisant sed?Comment remplacer quelques correspondances dans une ligne en utilisant sed

J'ai un file.log avec le texte:

 
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; 

Et je suis en train de remplacer somepath1/somepath_abc123/somepath3 dans chaque ligne.

Mais peu probable que les résultats est faux:

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

Comme vous pouvez voir les rendements sed que le dernier match.

J'ai essayé le code suivant:

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

Quel est le problème avec l'expression?

+0

parce que vous sed sed regex est gourmand. – ghostdog74

Répondre

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 

sortie

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

Merci ghostdog74. Cela fonctionne bien. Mais j'ai besoin d'utiliser sed pour la tâche en cours. – pathsag

3

Essayez d'utiliser [^ /] au lieu de.

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

Sinon, remplacez sed avec perl qui prend en charge une invocation comme sed:

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

où. ? est le même que . mais ce n'est pas gourmand.

+0

Merci marco! Remplacer [^ /] au lieu de. fonctionne parfaitement. Maintenant, j'ai prévu la sortie. – pathsag

Questions connexes