找到一个文件的内容到UNIX shell脚本的另一个文件 [英] finding contents of one file into another file in unix shell script

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

问题描述

我用下面的脚本找到一个文件的内容到另一个:

I'm using following shell script to find 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文件中包含一些如08915673123223这是在present CSV文件也是如此。这有什么错我在干嘛?

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 am I doing?

推荐答案

的grep 本身是能够做到这一点。只需使用标志 -f

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

grep -f <patterns> <file>

&LT;模式和GT; 是包含在每行一个模式的文件;和&LT;文件&gt; 是要搜索的东西文件

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

需要注意的是,强制的grep 来考虑每行的模式,即使每行的内容,看起来像一个普通的前pression,你应该使用标志 -F,--fixed串

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

以下命令的输出是:

The output of the following command is:

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

您不需要在所有 -loop这里; 的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.

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

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