How do I print a field from a pipe-separated file?

Or just use one command:

cut -d '|' -f FIELDNUMBER

The pipe character needs to be escaped so that the shell doesn't interpret it. A simple solution:

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

Another choice would be to quote the character:

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

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


Reading the comments I see that the original poster presents a simplified version of the original problem which involved filtering file before selecting and printing the fields. A pass through grep was used and the result piped into awk for field selection. That accounts for the wholly unnecessary cat file that appears in the question (it replaces the grep <pattern> file).

Fine, that will work. However, awk is largely a pattern matching tool on its own, and can be trusted to find and work on the matching lines without needing to invoke grep. Use something like:

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

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

The lost-looking {next;} is a default action skipping to the next line in the input. It does not seem to be necessary, but I have this habit from long ago...