我正在尝试获得以下输出。我有 2 个输入文件,我们只需要两个输入文件中的通用 :names 以及它们下面的行 .name/of/file 行。
到目前为止我已经尝试过:
awk 'FNR==NR { a[$1]; next }NF<=1{ flag=0 }$1 in a { print; flag=1; delete a[$1]; next }flag{ printf "%s\n",$0 }' file1 file2
输出:
:name1
./name/of/file [logfile] [ error in file coming since Day : 1 ]
./name/of/file [logfile] [ error in file coming since Day : 1 ]
:name3
./name/of/file [logfile] [ error in file coming since Day : 24 ]
./name/of/file [logfile] [ error in file coming since Day : 24 ]
:name4
./name/of/file [logfile] [ error in file coming since Day : 3 ]
./name/of/file [logfile] [ error in file coming since Day : 3 ]
./name/of/file [logfile] [ error in file coming since Day : 3 ]
./name/of/file [logfile] [ error in file coming since Day : 3 ]
输入文件1:
:name1
./name/of/file [logfile] [ error in file coming since Day : 1 ]
./name/of/file [logfile] [ error in file coming since Day : 1 ]
:name2
./name/of/file [logfile] [ error in file coming since Day : 1 ]
:name3
./name/of/file [logfile] [ error in file coming since Day : 24 ]
./name/of/file [logfile] [ error in file coming since Day : 24 ]
:name1
./name/of/file [logfile] [ error in file coming since Day : 40]
./name/of/file [logfile] [ error in file coming since Day : 40 ]
:name4
./name/of/file [logfile] [ error in file coming since Day : 3 ]
./name/of/file [logfile] [ error in file coming since Day : 3 ]
./name/of/file [logfile] [ error in file coming since Day : 3 ]
./name/of/file [logfile] [ error in file coming since Day : 3 ]
:name5
./name/of/file [logfile] [ error in file coming since Day : 6 ]
./name/of/file [logfile] [ error in file coming since Day : 6 ]
:name4
./name/of/file [logfile] [ error in file coming since Day : 10 ]
./name/of/file [logfile] [ error in file coming since Day : 10 ]
./name/of/file [logfile] [ error in file coming since Day : 10 ]
./name/of/file [logfile] [ error in file coming since Day : 10 ]
输入文件2:
:name1 ABC123 12345
:name3 EFG789 67898
:name4 HIJ547 01234
所需的输出文件:
:name1 ABC123 12345
./name/of/file [logfile] [ error in file coming since Day : 1 ]
./name/of/file [logfile] [ error in file coming since Day : 1 ]
:name3 EFG789 67898
./name/of/file [logfile] [ error in file coming since Day : 24 ]
./name/of/file [logfile] [ error in file coming since Day : 24 ]
:name4 HIJ547 01234
./name/of/file [logfile] [ error in file coming since Day : 3 ]
./name/of/file [logfile] [ error in file coming since Day : 3 ]
./name/of/file [logfile] [ error in file coming since Day : 3 ]
./name/of/file [logfile] [ error in file coming since Day : 3 ]
答案1
- 您的命令中有一个拼写错误:
file1
并且file2
应该被交换。 - 第一个字段作为索引保存在数组中
a
,但其余行(或$2
和$3
)作为值丢失。该值需要稍后打印。 - 缺少四个缩进空间来匹配您的预期输出。
老的:
awk '
FNR==NR { a[$1]; next }
NF<=1{ flag=0 }
$1 in a { print; flag=1; delete a[$1]; next }
flag{ printf "%s\n",$0 }
' file1 file2
新的:
awk '
FNR==NR { k=$1; $1=""; a[k]=$0; next }
NF<=1{ flag=0 }
$1 in a { print $0 a[$1]; flag=1; delete a[$1]; next }
flag{ print " " $0 }
' file2 file1