首先,让我声明我对 Bash 脚本非常陌生。我试图为我的问题寻找解决方案,但找不到任何对我有用的方法。
假设我想使用 bash 来解析如下所示的文件:
variable1 = value1
variable2 = value2
Run Code Online (Sandbox Code Playgroud)
我使用以下代码逐行拆分文件:
cat /path/to/my.file | while read line; do
echo $line
done
Run Code Online (Sandbox Code Playgroud)
$line我想从变量中创建一个数组,我想将它=作为分隔符进行拆分,这样我就可以像这样从数组中获取变量名和值:
$array[0] #variable1
$array[1] #value1
Run Code Online (Sandbox Code Playgroud)
什么是最好的方法来做到这一点?
将 IFS 设置为 '=' 以在您的行中分割 = 符号上的字符串,即:
cat file | while IFS='=' read key value; do
${array[0]}="$key"
${array[1]}="$value"
done
Run Code Online (Sandbox Code Playgroud)
您也可以使用 -a 参数来指定要写入的数组,即:
cat file | while IFS='=' read -a array; do
...
done
Run Code Online (Sandbox Code Playgroud)
bash 版本取决于。
为后代提供完全错误的旧答案:
将参数添加-d =到您的read语句中。然后你可以这样做:
cat file | while read -d = key value; do
$array[0]="$key"
$array[1]="$value"
done
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5122 次 |
| 最近记录: |