Home > Blockchain >  Extracting a specific string pattern from a list and get the corresponding row in the output file
Extracting a specific string pattern from a list and get the corresponding row in the output file

Time:11-27

my list.txt file has this format:

name  number
max   3

my test.txt file has this format:

position   name   hobby       number
postdoc    anna   tennis      2
grad       max    football    5
undergrad  timmy  rugby       1
teacher    max    jogging     3

How can I extract from test.txt using list.txt all lines where the names and numbers are matching, e.g.: I want to have max 3 from test.txt using list.txt extracted, so that the output will be teacher max jogging 3.

Max and 3 should appear in the same row.

Can you use grep or awk in this case, especially if you have a longer list than here?

CodePudding user response:

This one-liner should give you the result:

$  awk 'NR==FNR{a[$1]=$2;next}$2 in a && a[$2]==$NF' list.txt test.txt 
position   name   hobby       number
teacher    max    jogging     3

CodePudding user response:

I think @kent answer is much better, but you can also use this script:

cat list.txt | while read line; do
    grep "${line/ /[a-zA-Z ]*}" test.txt
done

CodePudding user response:

Using awk, you can try this for the expected output.

$ awk 'FNR==NR {array[$2$4]=$2FS$3FS$4; next}FNR > 1{print array[$1$2]}' test.txt list.txt
max jogging 3
  • Related