如何将文件中的指定行保存到变量中

huangapple go评论90阅读模式
英文:

How to save a specified line of a file to a variable

问题

I want to save a specified line of a file to a variable in bash script
example:

FileToReadFromThat.txt

  1. a
  2. b
  3. c
  4. d
  5. e

What I want to save in a simple line:

  1. variable="line 3 from $HOME/FileToReadFromThat.txt"

And result to get from that:

  1. $ echo $varible
  2. c
英文:

I want to save a specified line of a file to a variable in bash script
example:

FileToReadFromThat.txt

  1. a
  2. b
  3. c
  4. d
  5. e

What I want to save in a simple line:

  1. variable="line 3 from $HOME/FileToReadFromThat.txt"

And result to get from that:

  1. $ echo $varible
  2. c

答案1

得分: 2

使用awk尝试:

  1. VARIABLE=`awk 'NR==3' file`

或者使用sed:

  1. VARIABLE=`sed '3!d' file`
英文:

Try using awk:

  1. VARIABLE=`awk 'NR==3' file`

Or with sed

  1. VARIABLE=`sed '3!d' file`

答案2

得分: 1

  1. 或者使用 `cut`
  2. ```sh
  3. VARIABLE="$(<file cut -d $'\n' -f 3)"

或者使用Bash特定的read,对于小行数来说速度最快的方式:

  1. IFS=$'\n' read -r -d '' _ _ VARIABLE _ <file

或者使用Bash的mapfile,可能是最多功能且最快的方式,只使用Bash的内置命令而不派生子进程:

  1. mapfile -t -s 2 -n 1 VARIABLE <file
  1. <details>
  2. <summary>英文:</summary>
  3. Or `cut`:
  4. ```sh
  5. VARIABLE=&quot;$(&lt;file cut -d $&#39;\n&#39; -f 3)&quot;

Or using Bash specific read and the fastest for small line numbers

  1. IFS=$&#39;\n&#39; read -r -d &#39;&#39; _ _ VARIABLE _ &lt;file

or using Bash's mapfile and probably the most versatile and fastest way using only Bash's built-in commands without forking sub-processes:

  1. mapfile -t -s 2 -n 1 VARIABLE &lt;file

huangapple
  • 本文由 发表于 2020年1月6日 16:37:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/59608932.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定