【问题标题】:Read delimited multiline string file into multiple arrays in Bash将分隔的多行字符串文件读入 Bash 中的多个数组
【发布时间】:2019-03-01 13:41:30
【问题描述】:

我从这样的文件开始:

Table_name1 - Table_desc1
Table_name2 - Table_desc2
...
...

我有一个脚本可以解析这个文件并将它们分成两个数组:

declare -a TABLE_IDS=()
declare -a TABLE_DESCS=()

while IFS= read -r line || [[ -n "${line}" ]]; do
  TABLE_IDS[i]=${line%' '-' '*}
  TABLE_DESCS[i++]=${line#*' '-' '}
done < "${TABLE_LIST}"

for i in "${!TABLE_IDS[@]}"; do
        echo "Creating Table ID: "${TABLE_IDS[i]}", with Table Description: "${TABLE_DESCS[i]}""
done

这很好用,没有任何问题。

我想扩展它并制作文件:

Table_name1 - Table_desc1 - Table_schema1
Table_name2 - Table_desc2 - Table_schema2
...
...

为此,我尝试了:

declare -a TABLE_IDS=()
declare -a TABLE_DESCS=()

while IFS= read -r line || [[ -n "${line}" ]]; do
  TABLE_IDS[i]="$(echo $line | cut -f1 -d - | tr -d ' ')"
  TABLE_DESCS[i++]="$(echo $line | cut -f2 -d - | tr -d ' ')"
  TABLE_SCHEMAS[i++]="$(echo $line | cut -f3 -d - | tr -d ' ')"
done < "${TABLE_LIST}"

for i in "${!TABLE_IDS[@]}"; do
        echo "Creating Table ID: "${TABLE_IDS[i]}", with Table Description: "${TABLE_DESCS[i]}" and schema: "${TABLE_SCHEMAS[i]}""
done

虽然这将忠实地列出所有表 ID 和表描述,但省略了模式。我试过了:

while IFS= read -r line || [[ -n "${line}" ]]; do
  TABLE_IDS[i]="$(echo $line | cut -f1 -d - | tr -d ' ')"
  TABLE_DESCS[i]="$(echo $line | cut -f2 -d - | tr -d ' ')"
  TABLE_SCHEMAS[i]="$(echo $line | cut -f3 -d - | tr -d ' ')"
done < "${TABLE_LIST}"

它只返回最后一行的表名、描述和架构。我怀疑这是一个索引/循环问题,但我无法弄清楚到底出了什么问题。请帮忙!谢谢!

【问题讨论】:

  • 名称、描述和模式是否总是没有空格的字符串?
  • 循环中有两次i++

标签: arrays bash loops indexing


【解决方案1】:

也许将分隔符设置为实际的分隔符-,并在读取循环中进行处理,而不是延迟和使用数组。

$ while IFS=- read -r t d s; 
  do 
    echo "Creating Table ID: ${t// }, with Table Description: ${d// } and schema: ${s// }";
  done < file

【讨论】:

  • 完美运行!正如@Benjamin W. 上面所问的那样,我的表格描述中确实有空格。如果您可以尝试修改答案以保留描述词之间的空格,同时去除前导和尾随空格,那简直太棒了!不过,我正在寻找解决方案,所以...
  • 最终使用$( echo $d | xargs ) 进行描述。工作正常,并且是微创的。
  • 我用${t// }删除了空格,只是为了删除尾随空格更改为{t%%+( )}
  • 我需要删除前导和尾随空格。这是更简单的方法:)
猜你喜欢
  • 1970-01-01
  • 2012-03-06
  • 2016-12-27
  • 2021-12-17
  • 2018-05-01
  • 2012-04-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-29
相关资源
最近更新 更多