如何在Unix中使用带有多个字符分隔符的cut? [英] How to use cut with multiple character delimiter in Unix?
本文介绍了如何在Unix中使用带有多个字符分隔符的cut?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的文件看起来像这样
abc ||| xyz ||| foo bar
hello world ||| spam ham jam ||| blah blah
我要提取特定的列,例如我可以做到的:
I want to extract a specific column, e.g. I could have done:
sed 's/\s|||\s/\\t/g' file | cut -f1
但是还有另一种方法吗?
But is there another way of doing that?
推荐答案
由于 |
是有效的正则表达式,因此需要使用 \\ |
进行转义或放入在方括号中: [|]
.
Since |
is a valid regex expression, it needs to be escaped with \\|
or put in square brackets: [|]
.
您可以执行以下操作:
awk -F' \\|\\|\\| ' '{print $1}' file
其他一些也可以使用的变体:
Some other variations that work as well:
awk -F' [|][|][|] ' '{print "$1"}' file
awk -F' [|]{3} ' '{print "$1"}' file
awk -F' \\|{3} ' '{print "$1"}' file
awk -F' \\|+ ' '{print "$1"}' file
awk -F' [|]+ ' '{print "$1"}' file
\
作为分隔符在方括号中不能很好地工作,只能转义,并且许多转义字符:)
\
as separator does not work well in square brackets, only escaping, and many escape chars :)
cat file
abc \\\ xyz \\\ foo bar
示例:表达式中的每个 \
为4 \
,因此总共为12个 \
.
Example: 4 \
for every \
in the expression, so 12 \
in total.
awk -F' \\\\\\\\\\\\ ' '{print $2}' file
xyz
或
awk -F' \\\\{3} ' '{print $2}' file
xyz
或者这个,但是没有那么简单
or this but it's not much simpler
awk -F' [\\\\]{3} ' '{print $2}' file
xyz
awk -F' [\\\\][\\\\][\\\\] ' '{print $2}' file
xyz
这篇关于如何在Unix中使用带有多个字符分隔符的cut?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文