bash 如何使用管道字符分隔符分隔字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9018691/
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-18 01:25:56  来源:igfitidea点击:

How to separate fields with pipe character delimiter

bashsedawkpipeash

提问by morandg

I know this question has already been asked but no of the solution I've found worked for me! I have a program that has an output like this:

我知道已经有人问过这个问题,但我找到的解决方案都没有对我有用!我有一个程序,它有这样的输出:

COUNT|293|1|lps

I'm interested in having the second field however no one of these tries worked:

我对第二个领域很感兴趣,但是这些尝试都没有奏效:

./spawn 1 | cut -d '|' -f2
./spawn 1 | cut -d \| -f2
./spawn 1 | awk -F "|" '{print }'
./spawn 1 | awk 'BEGIN{FS="|"} {print }'
./spawn 1 | sed 's/|/;/g'
./spawn 1 | sed 's/\|/;/g'

But the output is always the same:

但输出总是相同的:

COUNT|293|1|lps

Is there a bug somewhere in bash? I would be surprised, the results is the same on my Linux host and on my embedded device using busybox's ash! Any pointer is strongly appreciated!

bash 中的某个地方是否存在错误?我会感到惊讶,结果在我的 Linux 主机和我的嵌入式设备上使用 busybox 的 ash 是一样的!强烈感谢任何指针!

EDITMy fault, the output was in stderr ... ._.

编辑我的错,输出在 stderr ... ._。

./spawn 1 2>&1 | cut -d '|' -f2
4615

Sorry for ennoying!

抱歉打扰了!

回答by Mark Longair

Just repeating what I guessed in a comment as an answer, now that the questioner has confirmed that this is the problem.

只是重复我在评论中的猜测作为答案,现在提问者已经确认这是问题所在。

The problem here is that ./spawn 1is outputting to standard error, not standard output. You can redirect the output using 2>&1, so the following should work:

这里的问题./spawn 1是输出到标准错误,而不是标准输出。您可以使用重定向输出2>&1,因此以下内容应该有效:

./spawn 1 2>&1 | cut -d '|' -f2

回答by morandg

$ echo 'COUNT|293|1|lps' | cut -d'|' -f2
293

It works here.

它在这里工作。