问题描述
如果我有一个字符串变量谁的值是约翰是17岁
我怎么记号化这使用空格作为分隔符?我会用 AWK
?
If I have a string variable who's value is "john is 17 years old"
how do I tokenize this using spaces as the delimeter? Would I use awk
?
推荐答案
使用shell的变量不带引号的自动标记化:
Use the shell's automatic tokenization of unquoted variables:
$ string="john is 17 years old"
$ for word in $string; do echo "$word"; done
john
is
17
years
old
如果你想改变你可以设置 $ IFS
变量,代表内部字段分隔的分隔符。 $ IFS
的默认值为\\ t \\ n
(空格,制表符,换行符)。
If you want to change the delimiter you can set the $IFS
variable, which stands for internal field separator. The default value of $IFS
is " \t\n"
(space, tab, newline).
$ string="john_is_17_years_old"
$ (IFS='_'; for word in $string; do echo "$word"; done)
john
is
17
years
old
(注意,在我周围添加第二行括号内第二个例子中,这将创建一个子shell,这样更改为 $ IFS
不存在。您一般不希望永久更改 $ IFS
,因为它可以发泄对不知情的shell命令破坏。)
(Note that in this second example I added parentheses around the second line. This creates a sub-shell so that the change to $IFS
doesn't persist. You generally don't want to permanently change $IFS
as it can wreak havoc on unsuspecting shell commands.)
这篇关于击:如何来标记一个字符串变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!