【问题标题】:How to get the nth line from a file and save the result to a variable [duplicate]如何从文件中获取第 n 行并将结果保存到变量 [重复]
【发布时间】:2019-03-28 15:02:53
【问题描述】:

所以,我正在 bash 中创建一个脚本,并尝试读取保存在同一目录中的文本文件。我需要读取该文件的nth 行,然后将其保存到一个变量中以供以后使用,但我不确定我该怎么做

下面列出了我当前尝试的内容,但它实际上是从文件中读取该行,将其保存为变量,然后从文件中删除该行并重复。这是一个 hack,虽然它有效,但不是我想要的,我无法获得 nth value,它正在从我绝对不想要的文件中删除。

read -r first<"test.txt"      // reads first line and stores in first
sed -i -e "1d" "test.txt" .   // removes first line
read -r second<"test.txt"     // reads first line and stores in second  
sed -i -e "1d" "test.txt" .   // removes first line

例如,如果我想获得第二行,我已经看到 sed '2q;d' file 但不确定结果的保存方式/位置。它在终端打印?任何帮助表示赞赏,谢谢!w

【问题讨论】:

  • 你也可以把 sed 写成sed -n '2{p;q}' 我觉得(有点)更明显。

标签: bash shell terminal


【解决方案1】:
sed '2q;d' file

file 中的第二行打印到终端。

要使用它填充变量,请使用 bash 的命令扩展功能:

$ var=$(sed '2q;d' file)
$ echo "$var"
this is second line

【讨论】:

    【解决方案2】:

    使用headtail 的简单解决方案:

    a=$(head -2 test.txt | tail -1 )
    

    将 test.txt 的第二行保存到变量 $a

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      • 2017-07-03
      • 2014-02-25
      • 1970-01-01
      • 1970-01-01
      • 2019-08-30
      相关资源
      最近更新 更多