【问题标题】:Using array from an output file in bash shell在 bash shell 中使用输出文件中的数组
【发布时间】:2019-06-30 17:31:04
【问题描述】:

我需要使用数组来设置变量值,以便从输出文件中进行进一步操作。

场景:

> 1. fetch the list from database 
> 2. trim the column using sed to a file named x.txt (got specific value as that is required)
> 3. this file x.txt has the below output as
10000 
20000 
30000
> 4. I need to set a variable and assign the above values to it.  
A=10000 
B=20000 
C=30000
> 5. I can invoke this variable A,B,C for further manipulations.

请告诉我如何定义一个从输出文件分配给它的变量的数组。

谢谢。

【问题讨论】:

  • 你想写一个shell脚本吗?对于哪个壳?见stackoverflow.com/a/30988704/10622916
  • 看起来你想要 3 个变量,分别命名为 A、B 和 C。数组在哪里?
  • 具体来说,x.txt 文件包含以下值 10.20.30.40 20.30.40.50 我希望将上述输出分配给一个变量,例如 SET[i] SET1=10.20.30.40 SET2=20.30。 40.50 所以我可以调用 SET1 和 SET2 进行进一步的操作。
  • @Bodo - 感谢它使用 mapfile -t 的链接。
  • 我可以将其复制到答案中,以使该问题对其他人更有用。我建议添加一个bash 标签。

标签: arrays bash unix


【解决方案1】:

bash(从版本4.x开始)你可以使用mapfile命令:

mapfile -t myArray < file.txt

https://stackoverflow.com/a/30988704/10622916

或旧 bash 版本的另一个答案:https://stackoverflow.com/a/46225812/10622916

【讨论】:

    【解决方案2】:

    我不太支持在 bash 中使用数组(如果您的代码足够复杂以至于需要数组,那么它也足够复杂以至于需要更健壮的语言),但您可以这样做:

    $ unset a
    $ unset i
    $ declare -a a
    $ while read line; do a[$((i++))]="$line"; done < x.txt
    

    (我已将交互式提示留在原处。删除前导 $ 如果你想把它放在一个脚本中。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-22
      • 2020-07-10
      • 2015-04-07
      • 1970-01-01
      • 1970-01-01
      • 2012-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多