如何避免使用 cut 命令前导 space?
How to avoid leading space using cut command?
要求:我只需要使用grep
/cut
/join
.
我有这样的数据:
3 abcd
23 xyz
1234 abc
我想将此数据传输到 cut
,然后提取列。但是,当我使用 cut -d' ' -f 1,2
时,它会将每个 space 视为其自己的列分隔符。我希望在 cut
之前修剪前两行。有办法吗?
示例(我使用 tr
来演示此处 space 的位置;解决方案中不允许这样做):
$ echo ' 3 abcd
23 xyz
1234 abc' | cut -d' ' -f 1,2 | tr ' ' '_'
_
_23
1234_abc
预期输出:
abcd
23 xyz
1234 abc
仅使用 grep
,您可以使用以下管道完成此操作:
grep -oe "[^ ][^ ]* *[^ ][^ ]*$"
grep # a tool for matching text
-o # only prints out matching text
-e # uses a regex
[^ ] # match anything that isn't a space
* # match zero or more of the previous element
$ # the end of the line
注意:这不考虑尾随空格。
示范:
$ echo ' 3 abcd
23 xyz
1234 abc' | grep -oe "[^ ][^ ]* *[^ ][^ ]*$"
3 abcd
23 xyz
1234 abc
要求:我只需要使用grep
/cut
/join
.
我有这样的数据:
3 abcd
23 xyz
1234 abc
我想将此数据传输到 cut
,然后提取列。但是,当我使用 cut -d' ' -f 1,2
时,它会将每个 space 视为其自己的列分隔符。我希望在 cut
之前修剪前两行。有办法吗?
示例(我使用 tr
来演示此处 space 的位置;解决方案中不允许这样做):
$ echo ' 3 abcd
23 xyz
1234 abc' | cut -d' ' -f 1,2 | tr ' ' '_'
_
_23
1234_abc
预期输出:
abcd
23 xyz
1234 abc
仅使用 grep
,您可以使用以下管道完成此操作:
grep -oe "[^ ][^ ]* *[^ ][^ ]*$"
grep # a tool for matching text
-o # only prints out matching text
-e # uses a regex
[^ ] # match anything that isn't a space
* # match zero or more of the previous element
$ # the end of the line
注意:这不考虑尾随空格。
示范:
$ echo ' 3 abcd
23 xyz
1234 abc' | grep -oe "[^ ][^ ]* *[^ ][^ ]*$"
3 abcd
23 xyz
1234 abc