bash - 用空格解析var

标签 bash shell

我有一个变量

some_var="a23=some value&p44=another_value&uw=possibly_another one"

我想将它转换成几个子字符串,每个 = 一个(在 & 处中断)。所以我会得到

a23=some value
p44=another_value
uw=possibly_another one

如果我运行这段代码

for s in ${some_var//&/ };do echo $s;done

我明白了

a23=some 
value
p44=another_value
uw=possibly_another
one

(它在空白处中断)

如何运行循环以考虑空间?

最佳答案

read 使用 '&' 作为字段分隔符:

#!/bin/bash

some_var='a23=some value&p44=another_value&uw=possibly_another one'
IFS='&' read -r -a arr <<< "$some_var"
for s in "${arr[@]}"; do
    printf '%s\n' "$s"
done

类似于你的技术也可以工作:

(IFS='&'; for s in $some_var; do printf '%s\n' "$s"; done)

注意它在一个子shell中运行,不要弄乱当前shell的IFS

您可以考虑阅读 this article IFS 的详细信息。

关于bash - 用空格解析var,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66233130/

相关文章:

linux - 如何打印特定用户的UID、GID?

windows - 如何从命令行使用 svn+ssh 和 Tortoise SVN

shell - 狂欢 : Search for specific special character in string

bash 脚本 - 无法在值中使用双引号设置变量

bash - 从 zsh 进入 bash 时如何加载 ~/.bash_profile?

linux - 超时命令 - 回显 shell 脚本的输出

linux - Linux 中匹配数据然后打印某些数据的最佳命令

bash - 将左侧故障通知管道的右侧?

Shell 脚本对文件中的行进行编号

linux - 需要在 bash shell linux 中比较当前时间