bash 从文件中读取行,然后使用这些值搜索不同的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17954908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read lines from a file then search a different file using those values
提问by Fr0ntSight
I have a file with a list of names in it (names.txt
) and I have a file with thousands of lines of tab seperated values (CallLog.tsv
). I need to grep
each name in names.txt
using the CallLog.tsv
file and then save that as a new file.
我有一个包含名称列表的文件 ( names.txt
),我有一个包含数千行制表符分隔值 ( CallLog.tsv
) 的文件。我需要使用该文件的grep
每个名称,然后将其另存为一个新文件。names.txt
CallLog.tsv
Right now I am doing the names individually:
现在我正在单独命名:
grep "John" CallLog.tsv > JohnCallLogs
Then I am taking all the names and cat
'ing them to another file:
然后我把所有的名字cat
都放到另一个文件中:
cat "John" "Mike" "Dave > FilteredCallLogs
I want to write a script to make this more efficient. I appreciate any help.
我想写一个脚本来提高效率。我很感激任何帮助。
回答by chepner
Instead of calling grep
multiple times (once per name), use the -f
option to find all matches in one call:
grep
使用该-f
选项在一次调用中查找所有匹配项,而不是多次调用(每个名称一次):
grep -f names.txt CallLog.tsv > FilteredCallLogs.tsv
If you need the lines grouped by name, you can sort the result on the proper field:
如果您需要按名称分组的行,您可以在适当的字段上对结果进行排序:
# E.g., if the names are in column 2
grep -f names.txt CallLog.tsv | sort -k2,2 > FilteredCallLogs.tsv
回答by Ansgar Wiechers
Try something like this:
尝试这样的事情:
#!/bin/bash
while read name; do
grep "$name" CallLog.tsv
done <names.txt >FilteredCallLogs.tsv
<names.txt
feeds names.txt
into the loop where while read name
reads it line-by-line into the loop variable $name
. >FilteredCallLogs.tsv
redirects the output from the loop into the file FilteredCallLogs.tsv
.
<names.txt
进料names.txt
入回路,其中while read name
读取它行由行成循环变量$name
。>FilteredCallLogs.tsv
将循环的输出重定向到文件中FilteredCallLogs.tsv
。