【问题标题】:Reading A File, And Extracting Each Line As It's Own Variable [Bash]读取文件,并提取每一行作为它自己的变量 [Bash]
【发布时间】:2014-03-02 13:06:24
【问题描述】:

我一直坚持这一点,似乎找不到任何好的技巧来让它发挥作用。 好的,所以我有一个名为“tweets”的文件,它有几百行。我需要将每一行作为它自己的变量。

例子:

   root@host:~$ cat tweets
   this is line one
   this is line two
   this is line three

好的,所以我需要将每一行设置为一个变量。谢谢!

【问题讨论】:

    标签: string bash file variables grep


    【解决方案1】:

    在 bash 中,使用mapfile 将文件读入数组:

    $ mapfile -t var < tweets
    $ echo "${var[0]}"
       this is line one
    $ echo "${var[2]}"
       this is line three
    

    【讨论】:

    • 是 BASH 4+ 功能,因为我在 GNU bash, version 3.2.48(1)-release 上没有它
    • 不知道。你能做到:a=(1); a+=(2) 吗?否则我会做while read -r line; do var[i++]=$line; done &lt; file
    • 然后:while read -r line; do var+=("$line"); done &lt; file。当然,这都是假设 OP 需要存储所有行,而不是您的答案。
    • 我也不确定是否要存储零件。
    【解决方案2】:

    你可以使用:

    while read line; do
        echo "$line"
    done < tweets
    

    【讨论】:

    • 那么变量是自动设置为“$line”,还是我必须设置?
    猜你喜欢
    • 2019-03-17
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 2013-03-26
    • 2021-10-18
    • 2020-08-15
    • 1970-01-01
    • 2018-02-07
    相关资源
    最近更新 更多