【问题标题】:How to read a file line by line into a variable without a loop如何在没有循环的情况下将文件逐行读入变量
【发布时间】:2018-11-09 21:51:15
【问题描述】:

所以你知道吗? Read a file line by line assigning the value to a variable

你如何在没有循环的情况下做到这一点,我处于循环会导致错误和混乱的情况。(如果你曾经尝试过使用并行)但我仍然需要逐行读取文件。

有没有什么方法可以在没有循环的情况下做到这一点? xargs? awk? parallel?

【问题讨论】:

  • 没有循环就无法逐行阅读。这是不可能的。即使您一次将整个文件读入内存,要逐行处理它,您也需要一个循环。你的问题没有意义。如果你的代码写得太糟糕以至于循环会导致错误和混乱,请先修复你的代码,然后添加循环。
  • 您可以使用readarray 将文件读入数组。
  • 记得以这样的方式提问,以便答案对您有用。你完全可以做到parallel 'var={}; echo "$var"' < file 完全符合这个问题,但对于现实世界的脚本来说,它可能会很慢、不适用或很愚蠢
  • @thatotherguy 赞成引用 " 空格和\n 正确。

标签: bash file loops xargs gnu-parallel


【解决方案1】:

使用readarray 将整个文件读入一个数组变量。每行都是一个数组元素。

readarray -t arrayname < filename

【讨论】:

  • 它的同义词mapfile 也可以在这里添加它的使用。两者之间缺乏区别总是有点令人费解。我能看到的唯一明显区别是mapfile 将使用环境变量MAPFILE 作为数组。
  • @DavidC.Rankin 它甚至有那个区别吗? readfile 文档说该变量是可选的,所以我假设它的默认值相同。文档暗示mapfile 是首选名称,但我通常看到人们使用readarray(名称似乎更直观)。
【解决方案2】:

这个问题对我来说真的没有多大意义,但你当然可以这样做:

{
read line_one <&3; # Read from the input file
echo "The first line is $line_one"
read line_two -u 3;  # A different method to read
echo "The second line in $line_two"
...
} 3< input file

请注意,实际上并没有必要从 fd 3 读取,但如果您的命令不是从与读取相同的输入读取,它会更安全。

但是,如果您确实“处于循环会导致错误和混乱的情况”,那么您遇到的问题不是解决方案。

【讨论】:

    【解决方案3】:

    FWIW,使用递归函数(好吧,递归可能是一个循环......)。首先是一些测试材料:

    $ seq 1 4 > file
    

    然后是函数fun:

    $ fun() {
        if read -r line <&5      # read from defined FD 5
        then 
            echo process $line   # process the lines here
            fun                  # recursive function call
        fi
    }
    

    呼叫fun

    $ exec 5< file
    $ fun
    process 1
    process 2
    process 3
    process 4
    $ exec 5<&-                  # close the FD
    

    【讨论】:

      【解决方案4】:

      有点不清楚你在问什么。也许您只是要求:

      myvar="$(cat thefile)"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-25
        • 2019-07-09
        • 2023-03-03
        • 2012-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-13
        相关资源
        最近更新 更多