如何打印管道分隔文件中的字段?
我有一个文件,其中的字段由管道字符分隔,我只想打印第二个字段。 这次尝试失败了:
$ cat file | awk -F| '{print $2}'
awk: syntax error near line 1
awk: bailing out near line 1
bash: {print $2}: command not found
有办法做到这一点吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
或者只使用一个命令:
Or just use one command:
这里的关键点是管道字符 (
|
) 必须转义到 shell。 使用“\|
”或“'|'
”来保护它免受 shell 解释,并允许它在命令行上传递给awk
。阅读评论,我发现原始海报提出了原始问题的简化版本,其中涉及在选择和打印字段之前过滤
文件
。 使用了grep
传递,并将结果通过管道传输到 awk 中进行字段选择。 这就解释了问题中出现的完全不必要的cat 文件
(它替换了grep文件
)。好吧,那会起作用的。 然而,awk 本身在很大程度上是一个模式匹配工具,可以信任它可以查找并处理匹配行,而无需调用
grep
。 使用如下内容://
位告诉awk
在匹配
的行上执行后续操作。看起来丢失的
{next;}
是跳到输入中的下一行的默认操作。 好像没有必要,但是我很久以前就有这个习惯了……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 toawk
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 throughgrep
was used and the result piped into awk for field selection. That accounts for the wholly unnecessarycat file
that 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 tellsawk
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...管道字符需要转义,以便 shell 无法解释它。 一个简单的解决方案:
另一种选择是引用该字符:
The pipe character needs to be escaped so that the shell doesn't interpret it. A simple solution:
Another choice would be to quote the character:
使用 awk 的另一种方法
Another way using awk
并且“文件”不包含管道符号,因此它不打印任何内容。 您应该使用“cat file”或简单地在 awk 程序后面列出该文件。
And 'file' contains no pipe symbols, so it prints nothing. You should either use 'cat file' or simply list the file after the awk program.