How to print a field from a file divided by a channel?

I have a file with fields separated by pipe characters and I want to print only the second field. This attempt fails:

$ cat file | awk -F| '{print $2}' awk: syntax error near line 1 awk: bailing out near line 1 bash: {print $2}: command not found 

Is there any way to do this?

+6
unix bash shell awk ksh
source share
4 answers

The key point here is that the channel symbol ( | ) must be escaped into the shell. Use ' \| "or' '|' "to protect it from shell interference and allow it to be passed to awk on the command line.


Looking at the comments, I see that the original poster is a simplified version of the original problem, which included filtering the file before selecting and printing the fields. A pass through grep , and the result was passed to awk to select the field. This explains the completely unnecessary cat file that appears in the question (it replaces grep <pattern> file ).

Ok, that will work. However, awk is basically a pattern matching tool, and you can trust it to find and work with the appropriate lines without having to call grep . Use something like:

 awk -F\| '/<pattern>/{print $2;}{next;}' file 

The bit /<pattern>/ tells awk to perform an action that follows the lines that correspond to <pattern> .

Lost {next;} is the default action, which moves to the next line in the input. It does not seem necessary, but I have this habit a long time ago ...

+9
source share

Or just use one command:

 cut -d '|' -f FIELDNUMBER 
+16
source share

The pipe symbol must be escaped so that the shell does not interpret it. A simple solution:

 $ awk -F\| '{print $2}' file 

Another option would be to quote a character:

 $ awk -F'|' '{print $2}' file 
+3
source share

And the β€œfile” does not contain channel characters, so it does not print anything. You must either use the "cat file" or simply list the file after the awk program.

0
source share

All Articles