Skip to content
Advertisement

How to feed awk input from both pipe and file?

I was wondering how do I get awk to take a string from the pipe output and a file?

I’ve basically have a chain of commands that eventually will spit out a string. I want to check this string against a csv file (columns separated by commas). Then, I want to find the first row in the file that contains the string in the 7th column of the csv file and print out the contents of the 5th column of that line. Also, I don’t know linux command line utilities/awk too well, so feel free to suggest completely different methods. 🙂

CSV file contents look like this:

col1,col2,col3,col4,col5,etc...
col1,col2,col3,col4,col5,etc...
etc...

My general line of thought:

(rest of commands that will give a string) | awk -F ',' 'if($5 == string){print $7;exit}' filename.txt

Can this be done? If so, how do I tell awk to compare against that string? I’ve found some stuff about using a - symbol with ARGV[] before the filename, but couldn’t get it working.

Advertisement

Answer

As Karoly suggests,

str=$( rest of commands that will give a string )
awk -v s="$str" -F, '$7==s {print $5; exit}' file

If you want to feed awk with a pipe:

cmds | awk -F, 'NR==FNR {str=$0; next}; $7==str {print $5}' - file

I think the first option is more readable.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement