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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:04:21  来源:igfitidea点击:

Read lines from a file then search a different file using those values

bashcsvgrepcat

提问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 grepeach name in names.txtusing the CallLog.tsvfile and then save that as a new file.

我有一个包含名称列表的文件 ( names.txt),我有一个包含数千行制表符分隔值 ( CallLog.tsv) 的文件。我需要使用该文件的grep每个名称,然后将其另存为一个新文件。names.txtCallLog.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 grepmultiple times (once per name), use the -foption 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.txtfeeds names.txtinto the loop where while read namereads it line-by-line into the loop variable $name. >FilteredCallLogs.tsvredirects the output from the loop into the file FilteredCallLogs.tsv.

<names.txt进料names.txt入回路,其中while read name读取它行由行成循环变量$name>FilteredCallLogs.tsv将循环的输出重定向到文件中FilteredCallLogs.tsv