use*_*111 5 bash shell awk sed
如果我们有第一个文件如下:
(a.txt)
1 asm
2 assert
3 bio
4 Bootasm
5 bootmain
6 buf
7 cat
8 console
9 defs
10 echo
Run Code Online (Sandbox Code Playgroud)
第二个像:
(b.txt)
bio cat BIO bootasm
bio defs cat
Bio console
bio BiO
bIo assert
bootasm asm
bootasm echo
bootasm console
bootmain buf
bootmain bio
bootmain bootmain
bootmain defs
cat cat
cat assert
cat assert
Run Code Online (Sandbox Code Playgroud)
我们希望输出如下:
3 7 3 4
3 9 7
3 8
3 3
3 2
4 1
4 10
4 8
5 6
5 3
5 5
5 9
7 7
7 2
7 2
Run Code Online (Sandbox Code Playgroud)
我们读取第一个文件中每个文件中的每个第二列,我们搜索它是否存在于第二个文件中每行的每一列中,如果是,我们将其替换为第一个文件中第一列中的数字.我只是在第一列中做到了,我不能为其余部分做到这一点.
这里命令我使用awk'NR == FNR {a [$ 2] = $ 1; next} {$ 1 = a [$ 1];} 1'a.txt b.txt
3 cat bio bootasm
3 defs cat
3 console
3 bio
3 assert
4 asm
4 echo
4 console
5 buf
5 bio
5 bootmain
5 defs
7 cat
7 assert
7 assert
Run Code Online (Sandbox Code Playgroud)
我该怎么做其他专栏?
谢谢
awk 'NR==FNR{h[$2]=$1;next} {for (i=1; i<=NF;i++) $i=h[$i];}1' a.txt b.txt
Run Code Online (Sandbox Code Playgroud)
NR是所有文件的全局记录号(默认行号).FNR是当前文件的行号.该NR==FNR块指定当全局行号等于当前数时要采取的操作,该操作仅对第一个文件为真,即a.txt.next此块中的语句会跳过其余代码,因此for循环仅可用于第二个文件ei,b.txt.
首先,我们处理第一个文件,以便将单词id存储在关联数组中:NR==FNR{h[$2]=$1;next}.之后,我们可以使用这些ID来映射第二个文件中的单词.for循环(for (i=1; i<=NF;i++) $i=h[$i];)遍历所有列并将每列设置为数字而不是字符串,因此$i=h[$i]实际上将第i列中的单词替换为其id.最后,1脚本末尾会打印出所有行.
生产:
3 7 3 4
3 9 7
3 8
3 3
3 2
4 1
4 10
4 8
5 6
5 3
5 5
5 9
7 7
7 2
7 2
Run Code Online (Sandbox Code Playgroud)
要使脚本不区分大小写,请将tolower调用添加到数组索引中:
awk 'NR==FNR{h[tolower($2)]=$1;next} {for (i=1; i<=NF;i++) $i=h[tolower($i)];}1' a.txt b.txt
Run Code Online (Sandbox Code Playgroud)