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?
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 toawkon the command line.Reading the comments I see that the original poster presents a simplified version of the original problem which involved filtering
filebefore selecting and printing the fields. A pass throughgrepwas used and the result piped into awk for field selection. That accounts for the wholly unnecessarycat filethat appears in the question (it replaces thegrep <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:The
/<pattern>/bit tellsawkto 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…