1

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
kvantour
  • 25,269
  • 4
  • 47
  • 72
mr459
  • 29
  • 4
  • 2
    Does this answer your question? [Bash tool to get nth line from a file](https://stackoverflow.com/questions/6022384/bash-tool-to-get-nth-line-from-a-file) in combination with [How do I set a variable to the output of a command in Bash?](https://stackoverflow.com/questions/4651437/) – kvantour Jan 06 '20 at 10:56

2 Answers2

2

Try using awk:

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

Or with sed

VARIABLE=`sed '3!d' file`
jeprubio
  • 17,312
  • 5
  • 45
  • 56
  • 2
    If your file is several GB big, you might be interested in `var=$(awk '(NR==3){print;exit}' file)` – kvantour Jan 06 '20 at 10:53
1

Or cut:

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
Léa Gris
  • 17,497
  • 4
  • 32
  • 41