shell 如何打印一个字符串和该字符串bash脚本的所有n行

vql8enpb  于 2023-02-13  发布在  Shell
关注(0)|答案(2)|浏览(208)

大家好,请帮助我,我正试图得到以下输出,所以基本上我有2个输入文件,我们只需要共同的:名称从两个输入文件以及下面的行。名称/的/文件行。
到目前为止,我已经尝试过:

awk '/:name1/{flag=1} flag;/ /{flag=0}' /path/of/input/file1

输出:

:name1
    ./name/of/file [logfile] [ error in file coming since Day : 1 ]

但它只打印了第一行。

    • 输入文件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 ]

: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 ]
    • 输入文件2:**
:name1
:name3
:name4
    • 所需输出文件**:
: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 ]
bxgwgixi

bxgwgixi1#

一种awk方法:

awk '
FNR==NR { a[$1]; next }
NF<=1   { flag=0   }           # clear flag if zero or one non-white-space fields is present in the current line
$1 in a { flag=1   }           # set flag if 1st field is an index in the a[] array
flag                           # if flag == 1 then print current line to stdout
' file2 file1

这将产生:

: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 ]
2eafrhcq

2eafrhcq2#

输出也可以缩进:

awk 'NR == FNR { for (i = 1; i <= NF; ++i) a[$i] = 1; next }
    a[$1] { $1 = $1; print }' RS= FS='\n' OFS='\n\t' file{2,1}

相关问题