2

So, I am creating a script in bash and I am trying to read a text file which is saved in the same directory. I need to read the nth line of that file and then save it to a variable to be used later but I'm not sure how I can do this

What I have currently tried is listed below but it essentially reads the line from the file, saves it a variable and then deletes that line from the file and repeats. This is a hack and although it works, isn't what I want, I can't get the nth value and it's deleting from the file which I definitely don't want.

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

If I wanted to get the 2nd line for example, I have seen sed '2q;d' file but not sure how/where the result is saved. It gets printed in terminal? Any help appreciated, thanks!w

Nouman
  • 585
  • 1
  • 11
  • 24

2 Answers2

3
sed '2q;d' file

prints the second line in file to the terminal.

To populate a variable with it, use bash's command expansion feature:

$ var=$(sed '2q;d' file)
$ echo "$var"
this is second line
oguz ismail
  • 1
  • 16
  • 47
  • 69
1

Simple solution using head and tail:

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

Saves the second line of test.txt to the variable $a.

mttpgn
  • 327
  • 6
  • 17