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

1
  • You can also write that sed as sed -n '2{p;q}' which I find (a little) more obvious. Commented Mar 28, 2019 at 15:58

2 Answers 2

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 
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.