How do I print a field from a pipe-separated file?
awk, bash, ksh, shell, unix
Solution
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...
Problem
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 a way to do this?