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

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

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

a
b
c
d
e

What I want to save in a simple line:

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

And result to get from that:

$ echo $varible
c
英文:

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

FileToReadFromThat.txt

a
b
c
d
e

What I want to save in a simple line:

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

And result to get from that:

$ echo $varible
c

答案1

得分: 2

使用awk尝试:

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

或者使用sed:

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

Try using awk:

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

Or with sed

VARIABLE=`sed '3!d' file`

答案2

得分: 1

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

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

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

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

mapfile -t -s 2 -n 1 VARIABLE <file

<details>
<summary>英文:</summary>

Or `cut`:

```sh
VARIABLE=&quot;$(&lt;file cut -d $&#39;\n&#39; -f 3)&quot;

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

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:

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:

确定