1

need help for grep -f to run in for loop

basically for each entry in name.txt, I want to grep all the line(s) from A.txt and write out for in separate files

For example 1) name.txt is a list of three following names

America
Europe   
Asia

2) A.txt is(tab delimited)

X y Z America
x a b Asia
y b c America
a b c Europe
x y z Europe
a b c America

now taking each entry from name.txt file, search the corresponding line(s) in A.txt and return in three separate output files:

file1: X y Z America
       y b c America
       a b c America

file2: a b c Europe
       x y z Europe
file3: x a b Asia

may be writing it in script and execute with bash?

Thanks in advance!!!

2 Answers 2

2

Run the following script (as ./script.sh name.txt input.txt) where name.txt has the names and input.txt is your input file. the output files are saved as file_America.txt, file_Asia.txt and file_Europe.txt

#!/bin/bash -x

while read line; do
#skip empty line
[ -z "$line" ] && continue;
#run grep and save the output
grep "$line" "$2" > file_$line.txt;
done < "$1"
Sign up to request clarification or add additional context in comments.

2 Comments

Useless use of cat. Use input redirection: while read line; do ...; done < "$1"
@chepner: Or < $1 while read line; do ...; done. Yes, the redirection can go before the command, and in this case it makes it clearer.
0

One way using awk:

awk '
    ## Process first file of arguments. Save data in an array, the name as
    ## key, and the number of the output file to write as value.
    FNR == NR {
        name[ $1 ] = FNR;
        next;
    }

    ## Process second file of arguments. Check last field of the line in the 
    ## array and print to file matched by the value.
    FNR < NR {
        print $0 > sprintf( "%s%d", "file", name[ $NF ] );
    }
' name.txt A.txt

Check output files:

head file[123]

With following result:

==> file1 <==
X y Z America
y b c America
a b c America

==> file2 <==
a b c Europe
x y z Europe

==> file3 <==
x a b Asia

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.