簡體   English   中英

Bash:比較兩個文件並更改輸出

[英]Bash: compare two files and change the output

嘗試使用我的腳本修復輸出內容,但不起作用。
我們將這兩個文件命名為“文件A”和“文件B”
文件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

文件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 

還是可以通過其他命令實現?

您可以使用此:

grep -of file_B file_A | paste <(grep -f file_B file_A | cut -d' ' -f1,2 ) -

首先按FILE_BFILE_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

這個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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM