从文件的每一行取值并在另一个文件中搜索它在Unix?

toe95027  于 2023-06-22  发布在  Unix
关注(0)|答案(4)|浏览(136)

我有两个文件。我希望我的Unix代码将文件A中每一行的第一列作为变量,并在文件B中查找它。如果找到了,我希望将文件B中找到的行保存在输出文件中。

File A:
1335 skrgrsjgls 1231
12213 23rerwsdf 9605
11567 4693460 0340592
54321 293402460 324

File B: 
-54321 Apples
-23453 Grapes
-1335 Pears
-65363 Pineapples
-96506 Grapefruit

Expected Output File:
-1335 Pears
-54321 Apples

我试过的代码:

for i in $(cat File A); do grep -w $i File B > FileC; done

我没有得到任何结果。请任何帮助是赞赏。

cgh8pdjw

cgh8pdjw1#

希望对你有用。这可以使用grep命令来完成,该命令用于在文件中搜索模式。

for i in $(cat FileA.txt); do   grep -i "$i" FileB.txt >> output.txt; done

输出

HaLF-MenTaL@DESKTOP-7B47GH0 MINGW64 ~/Documents
$ for i in $(cat FileA.txt); do   grep -i "$i" FileB.txt >> output.txt; done

HaLF-MenTaL@DESKTOP-7B47GH0 MINGW64 ~/Documents
$ cat output.txt
-1335 Pears
-54321 Apples

这是您的测试命令的输出。

HaLF-MenTaL@DESKTOP-7B47GH0 MINGW64 ~/Documents
$ for i in $(cat FileA.txt); do grep -i "$i" FileB.txt | head -10; done
-1335 Pears
-54321 Apples
6l7fqoea

6l7fqoea2#

对于大文件,应该避免每行都有一个新的grep的循环。
awk是一个很好的工具,另一个解决方案是

grep -f <(sed -r 's/([^ ]*).*/^-\1 /' FileA) FileB

<(sed -r 's/([^ ]*).*/^-\1 /' FileA)部分创建了一种内存文件,其中包含您要查找的字符串(以^、连字符、数字、空格开始的行),grep -f file使用“文件”作为要查找的多个字符串。

2exbekwf

2exbekwf3#

好吧,下面的问题就解决了。我感谢所有为这个问题做出贡献的人,我相信他们的版本也是可行的。

while read -r line; do var=$(echo $line | awk '{print $1}') grep -w "$var" FileB > FileC; done < FileA
z3yyvxxp

z3yyvxxp4#

我同意对于大文件应该避免循环,并且awk是一个很好的替代方案。试着做:

awk 'FNR==NR { a[$1]=$0; next } $1 in a { print a[$1] }' FileB.txt FileA.txt > Output.txt

FNR==NR部分确保下一个块仅针对第一个文件执行,
{ a[$1]=$0; next }将FileB.txt的第一列保存为数组,
$1 in a将检查FileA.txt中是否存在该密钥,
{ print a[$1] }打印找到的匹配项,
FileB.txt FileA.txt是给出给CMD行的参数(注意顺序),
并且> Output.txt将该打印保存到输出文件。

相关问题