英文:
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="$(<file cut -d $'\n' -f 3)"
Or using Bash specific read
and the fastest for small line numbers
IFS=$'\n' read -r -d '' _ _ VARIABLE _ <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 <file
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论