Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 字符串变量中的第n个字_Bash - Fatal编程技术网

Bash 字符串变量中的第n个字

Bash 字符串变量中的第n个字,bash,Bash,在Bash中,我想获取由变量保存的字符串的第n个字 例如: STRING="one two three four" N=3 结果: "three" This is the 1st Statement This is the 2nd Statement This is the 3rd Statement This is the 4th Statement This is the 5th Statement 什么Bash命令/脚本可以做到这一点?另一种选择 echo $STRING | cut

在Bash中,我想获取由变量保存的字符串的第n个字

例如:

STRING="one two three four"
N=3
结果:

"three"
This is the 1st Statement
This is the 2nd Statement
This is the 3rd Statement
This is the 4th Statement
This is the 5th Statement
什么Bash命令/脚本可以做到这一点?

另一种选择

echo $STRING | cut -d " " -f $N
N=3
STRING="one two three four"

arr=($STRING)
echo ${arr[N-1]}
使用
awk

echo $STRING | awk -v N=$N '{print $N}'
试验


没有昂贵的叉子,没有管道,没有羞耻感:

$ set -- $STRING
$ eval echo \${$N}
three
或者,如果要避免
eval

$ set -- $STRING
$ shift $((N-1))
$ echo $1
three

但要注意全局绑定(使用
set-f
关闭文件名全局绑定)。

包含以下语句的文件:

cat test.txt
结果:

"three"
This is the 1st Statement
This is the 2nd Statement
This is the 3rd Statement
This is the 4th Statement
This is the 5th Statement
因此,要打印此语句类型的第四个单词:

awk '{print $4}' test.txt
输出:

1st
2nd
3rd
4th
5th

在您的示例中,字符串真的是字符串吗?它看起来像一个数组。@NicolasRaoul是的,实际上你是对的。但是我写的是作为一种替代。使用bash阵列是“最好”的解决方案,我讨厌使用awk或sed,因为我没有看到它们安装在所有的设置上,尤其是msys设置。尽管echo“不是必需的”,但我发现它对理解如何使用arr元素很有用。谢谢如果您已将
IFS
(内部字段分隔符)设置为“:”或其他内容而不是空白,请在尝试此操作之前将其更改回。这应该是正确的答案。为此目的使用数组既简单又聪明。请注意,如果“word”是“*”(),它将失败-它将带来当前目录中所有文件和所有目录的列表。当请求不存在的字段时,cut将失败。它将返回字符串本身,而不是返回“”。示例:echo“aaaa”| cut-f2结果为“aaaa”,而不是空的零长度结果。@ajaskel在输入中找不到分隔符时似乎会发生这种情况。现在,这种行为可以通过使用选项--only-delimited来改变。OP表示字符串在变量中,而不是在文件中。它是否处理其中一个“单词”为“*”?没有。@PeterMortensen它可以做到这两个。在
set-f
之后,如果不全局展开星号,则将使用
set+f
(默认值)展开星号。