【问题标题】:How to replace 3rd column given that first two column match鉴于前两列匹配,如何替换第三列
【发布时间】:2012-09-13 05:22:41
【问题描述】:

这就是我想要达到的目标:

文件1:

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

文件2:

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

file1 变成:

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

【问题讨论】:

    标签: bash scripting sed awk


    【解决方案1】:

    这可能对你有用(GNU sed):

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

    【讨论】:

      【解决方案2】:
      % 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;
      

      【讨论】:

        【解决方案3】:

        你可以试试:

        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
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-09-08
          • 2014-11-05
          • 1970-01-01
          相关资源
          最近更新 更多