Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to feed awk input from both pipe and file?

Tags:

linux

awk

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.

like image 706
XeroAura Avatar asked Oct 15 '15 00:10

XeroAura


People also ask

What is awk '{ print $1 }'?

awk '{print $1}' information. txt prints the first column. Then the output of that command (which you saw earlier on) is piped, using the pipe symbol | , to the head command, where its -1 argument selects the first line of the column. If you wanted two lines printed, you'd do: awk '{print $1}' information.txt | head -2.

What is awk '{ print $2 }'?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output.

How do I read a file line by line in awk?

Using getline from a Pipe You can pipe the output of a command into getline , using ` command | getline' . In this case, the string command is run as a shell command and its output is piped into awk to be used as input. This form of getline reads one record at a time from the pipe.

Can awk read from multiple files?

awk is a convenient and powerful command-line utility for processing text. Sometimes, we need to read and process multiple input files. In this tutorial, we'll learn how to process multiple input files using the awk command.


1 Answers

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.

like image 82
glenn jackman Avatar answered Sep 18 '22 08:09

glenn jackman