如果前两列匹配,如何替换第3列

时间:2012-09-20 19:22:12

标签: bash scripting sed awk

这就是我想要实现的目标:

文件1:

test fileb 4578;
test filec 7689;
test filey 9978;
test filez 12300;

file2的:

test fileb 1;
test filec 2;
test filey 3;

file1变为:

test fileb 1;
test filec 2;
test filey 3;
test filez 12300;

3 个答案:

答案 0 :(得分:0)

您可以尝试:

while read f1 f2 f3
do 
  X=$(grep "$f1 $f2" file2)
  if [ -n "$X" ]; then 
    echo "$X"
  else 
    echo "$f1 $f2 $f3"
  fi
done <file1

答案 1 :(得分:0)

% awk 'NR==FNR{a[$1,$2]=$3;next}{if(a[$1,$2])$3=a[$1,$2];print}' file2 file1
test fileb 1;
test filec 2;
test filey 3;
test filez 12300;

答案 2 :(得分:0)

这可能适合你(GNU sed):

sed 's|\(\S* \S*\).*|/\1/c\\&|' file2 | sed -i -f - file1