Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

linux - Finding contents of one file in another file

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"

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

grep -f <patterns> <file>

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

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>

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

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

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

alpha
0891234
beta

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

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


Now using your file names:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...