bash 如何从管道分隔文件打印字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/213855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 17:45:31  来源:igfitidea点击:

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

bashunixshellawkksh

提问by Jon Ericson

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 }'
awk: syntax error near line 1
awk: bailing out near line 1
bash: {print }: command not found

Is there a way to do this?

有没有办法做到这一点?

回答by Zsolt Botykai

Or just use one command:

或者只使用一个命令:

cut -d '|' -f FIELDNUMBER

回答by dmckee --- ex-moderator kitten

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 awkon the command line.

这里的关键点是管道字符 ( |) 必须转义到 shell。使用“ \|”或“ '|'”来保护它免受shell解释并允许它awk在命令行上传递。



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 through grepwas used and the result piped into awk for field selection. That accounts for the wholly unnecessary cat filethat appears in the question (it replaces the grep <pattern> file).

阅读评论我看到原始海报提出了原始问题的简化版本,其中涉及file在选择和打印字段之前进行过滤。使用了传递grep并将结果通过管道传输到 awk 以进行字段选择。这说明cat file了问题中出现的完全不必要的内容(它取代了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 本身在很大程度上是一种模式匹配工具,可以信任它可以查找和处理匹配行,而无需调用grep. 使用类似的东西:

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

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

/<pattern>/位告诉awk在匹配的行上执行后面的操作<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...

丢失查找{next;}是跳到输入中的下一行的默认操作。好像没必要,不过这个习惯我很久以前就有了……

回答by Jon Ericson

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

管道字符需要进行转义,以便 shell 不会解释它。一个简单的解决方案:

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

Another choice would be to quote the character:

另一种选择是引用字符:

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

回答by Mirage

Another way using awk

使用 awk 的另一种方式

awk 'BEGIN { FS = "|" } ; { print  }'

回答by Jonathan Leffler

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.

并且 'file' 不包含管道符号,因此它不打印任何内容。您应该使用 'cat file' 或简单地在 awk 程序之后列出该文件。