试图用我的脚本修复输出内容,但不工作..
我们将这两个文件命名为“文件A”和“文件B”
文件A是内容string,如:
C Test aa.test.com D Test bb.example.com G Test cc.try.example.com K Test dd.test.com M Test cc.ee.try.example.com O Test .test.com T Test gg-1-2.example.com U Test hh.example.com X Test example.com
文件B是:
test.com example.com try.example.com
尝试比较两个文件,并使输出如下所示:
C Test test.com D Test example.com G Test try.example.com K Test test.com M Test try.example.com O Test test.com T Test example.com U Test example.com X Test example.com
这是我的示例代码:
#!/bin/bash File_A="/root/temp/File_A" File_B="/root/temp/File_B" awk -v File_B="$File_B" -v OFS=" " ' BEGIN { while ( ( getline < File_B ) > 0 ){ VAL = $0 sub( /^[^ ]+ /, "", VAL ) DICT[ $1 ] = VAL } } { print $0, DICT[ $1 ] }' $File_A exit
输出后,我仍然得到了与文件A相同的内容,无法弄清楚。
C Test aa.test.com D Test bb.example.com G Test cc.try.example.com K Test dd.test.com M Test cc.ee.try.example.com O Test .test.com T Test gg-1-2.example.com U Test hh.example.com X Test example.com
或者可以通过其他命令实现?
这个awk
应该这样做:
awk 'FNR==NR {arr[$0];next} {for (i in arr) {c=match($3,i);n=c&&(!b[$3]||c<b[$3])?i:n;b[$3]=c}$3=n}1' File-B File-A C Test test.com D Test example.com G Test try.example.com K Test test.com M Test try.example.com O Test test.com T Test example.com U Test example.com X Test example.com
你可以使用这个:
grep -of file_B file_A | paste <(grep -f file_B file_A | cut -d' ' -f1,2 ) -
首先按行长度对FILE_B
进行排序并将其保存到FILE_C
:
cat FILE_B | awk '{ print length(), $0 }' | sort -nr | cut -d ' ' -f 2- > FILE_C
然后运行这个命令:
awk 'BEGIN{c=0;}FNR==NR{a[c++]=$0;next;} {for(i in a){if(match($3,a[i])){$3=a[i];print $0;next;} } }' FILE_C FILE_A
输出:
C Test test.com D Test example.com G Test try.example.com K Test test.com M Test try.example.com O Test test.com T Test example.com U Test example.com X Test example.com