现在我有2个文件:
File1中:
120111 A
120112 B
120113 C
120114 D
120115 E
File2:
aaa bb dd cc 120111
ccc ss ll ee 120111
sss cd ff ee 120111
bbb ek lw ss 120112
bbb kk ll ww 120112
wwo oo kk ww 120112
ww kkk jw ll 120113
www kk sl if 120114
wwk kl so as 120114
wei kk lw pz 120115
我希望得到这样的输出:
aaa bb dd cc 120111 A
ccc ss ll ee 120111 A
sss cd ff ee 120111 A
bbb ek lw ss 120112 B
bbb kk ll ww 120112 B
wwo oo kk ww 120112 B
ww kkk jw ll 120113 C
www kk sl if 120114 D
wwk kl so as 120114 D
wei kk lw pz 120115 E
我尝试使用循环和grep,但我坚持添加' A B C D E'在行尾。 这是我的代码,
while read line1 do Date=${line1:0:6} grep $Date File2 done < File1
如果有人知道如何解决这个问题,请帮助我。 谢谢!
答案 0 :(得分:2)
这是完成工作的awk
:
awk 'FNR==NR {a[$1]=$2;next} {print $0,a[$5]}' file1 file2
aaa bb dd cc 120111 A
ccc ss ll ee 120111 A
sss cd ff ee 120111 A
bbb ek lw ss 120112 B
bbb kk ll ww 120112 B
wwo oo kk ww 120112 B
ww kkk jw ll 120113 C
www kk sl if 120114 D
wwk kl so as 120114 D
wei kk lw pz 120115 E
它将第一个文件file1
存储在数组a
中,使用第一个字段作为索引,第二个作为数据。
然后它打印出来自file2
的数据并使用第五个字段从数组a
答案 1 :(得分:0)
我怀疑你的问题是一个路径问题,因为grep应该可以正常工作:
#!/bin/bash
## validate both input files are readable
[ -r "$1" -a -r "$2" ] || {
printf "\n error: invalid input. Usage: %s key_file srch_file\n\n" "${0//*\//}"
}
## read each line in the first (key_file)
while read -r key ltr || [ -n "$ltr" ]; do
## output the grep command being used followed by the results
printf "\n cmd: grep %s %s\n\n" "$key" "$2"
grep "$key" "$2"
done <"$1"
exit 0
<强>输出:强>
$ bash grepvalues.sh dat/grepkey.txt dat/grepfile.txt
cmd: grep 120111 dat/grepfile.txt
aaa bb dd cc 120111
ccc ss ll ee 120111
sss cd ff ee 120111
cmd: grep 120112 dat/grepfile.txt
bbb ek lw ss 120112
bbb kk ll ww 120112
wwo oo kk ww 120112
cmd: grep 120113 dat/grepfile.txt
ww kkk jw ll 120113
cmd: grep 120114 dat/grepfile.txt
www kk sl if 120114
wwk kl so as 120114
cmd: grep 120115 dat/grepfile.txt
wei kk lw pz 120115
当然,在printf
命令之前评论grep
会产生以下结果:
aaa bb dd cc 120111
ccc ss ll ee 120111
sss cd ff ee 120111
bbb ek lw ss 120112
bbb kk ll ww 120112
wwo oo kk ww 120112
ww kkk jw ll 120113
www kk sl if 120114
wwk kl so as 120114
wei kk lw pz 120115
在grep输出结束时添加字母
#!/bin/bash
## validate both input files are readable
[ -r "$1" -a -r "$2" ] || {
printf "\n error: invalid input. Usage: %s key_file srch_file\n\n" "${0//*\//}"
}
## read each line in the first (key_file)
while read -r key ltr || [ -n "$ltr" ]; do
## output the grep command being used followed by the results
#printf "\n cmd: grep %s %s\n\n" "$key" "$2"
while read -r ln; do
printf " %s %s\n" "$ln" "$ltr"
done <<<"$(grep "$key" "$2")"
done <"$1"
exit 0
<强>输出:强>
$ bash grepvalues.sh dat/grepkey.txt dat/grepfile.txt
aaa bb dd cc 120111 A
ccc ss ll ee 120111 A
sss cd ff ee 120111 A
bbb ek lw ss 120112 B
bbb kk ll ww 120112 B
wwo oo kk ww 120112 B
ww kkk jw ll 120113 C
www kk sl if 120114 D
wwk kl so as 120114 D
wei kk lw pz 120115 E