bash 在拆分后第二次出现

use*_*619 4 command-line text-processing

我想用“|”分割文本卷 作为空间并获得第二次出现即;值 - 'test2'

volumes=|test1|test2
echo $volumes | tr "|" "\n"
Run Code Online (Sandbox Code Playgroud)

上面的命令分成每一行..我可以遍历它并获取值但想要最有效的方式。

ste*_*ver 6

您可以使用 shell 的内置参数替换"${volumes##*|}"来删除最长匹配到一个|字符的初始字符串

$ volumes="|test1|test2"
$ echo "${volumes##*|}"
test2
Run Code Online (Sandbox Code Playgroud)

或者,有 cut

$ cut -d\| -f3 <<< "$volumes"
test2
Run Code Online (Sandbox Code Playgroud)

或者 awk

$ awk -F\| '{print $NF}' <<< "$volumes"
test2
Run Code Online (Sandbox Code Playgroud)