Finding the contents of one file to another file in a unix shell script

I use the following shell script to find the contents of one file to another:

#!/bin/ksh file="/home/nimish/contents.txt" while read -r line; do grep $line /home/nimish/another_file.csv done < "$file" 

I am running a script but not displaying the contents from the csv file. My contents.txt file contains a number, such as "08915673" or "123223" , which are also present in the csv file. Is something wrong I'm doing?

+9
linux unix shell grep awk
Feb 25 '13 at 2:59
source share
3 answers
Himself

grep can do this. Just use the -f flag:

 grep -f <patterns> <file> 

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

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

 grep -F -f <patterns> <file> 

If your CSV file, as you said, you can do:

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



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

 alpha 0891234 beta 

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

 Alpha 0808080 0891234 bEtA 

The output of the following command:

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

You don't need for -loop here at all; 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 ',' '\n' < "${patterns}") "${search}" 

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

+27
Feb 25 '13 at 3:02
source share
โ€” -

Another solution:

  • use awk , create your own hash (e.g. ahash), all control yourself.
  • replace $0 to $i , you can match any fields you want.



 awk -F"," ' { if (nowfile==""){ nowfile = FILENAME; } if(FILENAME == nowfile) { hash[$0]=$0; } else { if($0 ~ hash[$0]) { print $0 } } } ' xx yy 
+2
Feb 25 '13 at 10:07
source share

I donโ€™t think you really need a script to execute what you are trying to do.

One team is enough. In my case, I need to specify the identification number in column 11 in the csv file (with a separator ";" as a separator)

 grep -f <(awk -F";" '{print $11}' FILE_TO_EXTRACT_PATTERNS_FROM.csv) TARGET_FILE.csv 

Hope this helps.

+1
Sep 08 '17 at 18:09 on
source share



All Articles