如果我有一个字符串变量谁的值是"john is 17 years old"如何使用空格作为分隔符来标记它?我会用awk吗?
Die*_*ano 60
$ string="john is 17 years old"
$ tokens=( $string )
$ echo ${tokens[*]}
Run Code Online (Sandbox Code Playgroud)
对于其他分隔符,例如';'
$ string="john;is;17;years;old"
$ IFS=';' tokens=( $string )
$ echo ${tokens[*]}
Run Code Online (Sandbox Code Playgroud)
Joh*_*ica 53
使用shell对未加引号的变量进行自动标记:
$ string="john is 17 years old"
$ for word in $string; do echo "$word"; done
john
is
17
years
old
Run Code Online (Sandbox Code Playgroud)
如果要更改分隔符,可以设置$IFS变量,该变量代表内部字段分隔符.的默认值$IFS是" \t\n"(空格,制表,换行).
$ string="john_is_17_years_old"
$ (IFS='_'; for word in $string; do echo "$word"; done)
john
is
17
years
old
Run Code Online (Sandbox Code Playgroud)
(请注意,在第二个示例中,我在第二行附近添加了括号.这会创建一个子shell,因此更改$IFS不会持续存在.您通常不希望永久更改,$IFS因为它会对毫无疑问的shell命令造成严重破坏. )
kur*_*umi 10
$ string="john is 17 years old"
$ set -- $string
$ echo $1
john
$ echo $2
is
$ echo $3
17
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72939 次 |
| 最近记录: |