在bash脚本中使用空格拆分句子 [英] Split a sentence using space in bash script
问题描述
如何使用空格分割一个句子,然后从第二个单词开始打印?
How can I split a sentence using space, and print from second word onwards?
例如,如果我的句子是Hello World Good Morning
,那么我想打印如下:
For example, if my sentence is Hello World Good Morning
, then I want to print like:
World
Good
Morning
推荐答案
With cut
:
$ echo "Hello World Good Morning" | cut -d' ' -f2-
World Good Morning
这告诉 cut
根据 d
分隔符空间剪切"(令人惊讶地)并从第二个字段打印到结尾.
This tells cut
to "cut" (surprisingly) based on d
elimiter space and print from 2nd field up to the end.
使用sed
:
$ echo "Hello World Good Morning" | sed 's/^[^ ]* //'
World Good Morning
这会从行首 (^
) 获取一个不包含空格的字符块 ([^ ]*
),然后是一个空格并替换它的内容为空.这样,第一个词就被删除了.
This gets, from the beginning of the line (^
), a block of characters not containing a space ([^ ]*
) and then a space and replaces it with empty content. This way, the first word is deleted.
纯bash
:
$ while IFS=" " read -r _ b; do echo "$b"; done <<< "Hello World Good Morning"
World Good Morning
这会将字段分隔符设置为空格并读取虚拟变量 _
中的第一个块,以及变量 $b
中的其余部分.然后,它打印 $b
.
This sets the field separator to the space and reads the first block in a dummy variable _
and the rest in the variable $b
. Then, it prints $b
.
也在 awk
中,使用这个 Ed Morton 的方法:
Also in awk
, using this Ed Morton's approach:
$ echo 'Hello World Good Morning' | awk '{sub(/([^ ]+ +){1}/,"")}1'
World Good Morning
这将 1 块 非空格字符
+ 块 空格
替换为空字符串.
This replaces 1 block of not space characters
+ block of spaces
with an empty string.
这篇关于在bash脚本中使用空格拆分句子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!