在另一个文件中查找一个文件的内容 [英] Finding contents of one file in another file

查看:120
本文介绍了在另一个文件中查找一个文件的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下shell脚本将一个文件的内容查找到另一个文件中:

I'm using the following shell script to find the contents of one file into another:

#!/bin/ksh
file="/home/nimish/contents.txt"

while read -r line; do
    grep $line /home/nimish/another_file.csv
done < "$file"

我正在执行脚本,但是它没有显示CSV文件中的内容.我的contents.txt文件包含CSV文件中也存在的数字,例如"08915673""123223".我的工作有什么问题吗?

I'm executing the script, but it is not displaying the contents from the CSV file. My contents.txt file contains number such as "08915673" or "123223" which are present in the CSV file as well. Is there anything wrong with what I do?

推荐答案

grep本身可以做到.只需使用标志-f:

grep itself is able to do so. Simply use the flag -f:

grep -f <patterns> <file>

<patterns>是每行包含一个模式的文件; <file>是您要在其中搜索内容的文件.

<patterns> is a file containing one pattern in each line; and <file> is the file in which you want to search things.

请注意,要强制grep将每行视为一种模式,即使每行的内容看起来像是正则表达式,也应使用标志-F, --fixed-strings.

Note that, to force grep to consider each line a pattern, even if the contents of each line look like a regular expression, you should use the flag -F, --fixed-strings.

grep -F -f <patterns> <file>

如果您说的是CSV文件,则可以这样做:

If your file is a CSV, as you said, you may do:

grep -f <(tr ',' '\n' < data.csv) <file>


以一个示例为例,考虑文件"a.txt",其中包含以下几行:


As an example, consider the file "a.txt", with the following lines:

alpha
0891234
beta

现在,文件"b.txt"的内容如下:

Now, the file "b.txt", with the lines:

Alpha
0808080
0891234
bEtA

以下命令的输出是:

grep -f "a.txt" "b.txt"
0891234

您根本不需要在这里进行for循环; grep本身提供此功能.

You don't need at all to for-loop here; grep itself offers this feature.

现在使用您的文件名:

#!/bin/bash
patterns="/home/nimish/contents.txt"
search="/home/nimish/another_file.csv"
grep -f <(tr ',' '\n' < "${patterns}") "${search}"

您可以将','更改为文件中的分隔符.

You may change ',' to the separator you have in your file.

这篇关于在另一个文件中查找一个文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆