Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read the last line of a text file into a variable using Bash? [closed]

I want to read a text file called history.txt that contains multiple lines and store the content of the last line into a variable called "tag".

Thanks

like image 771
Tommy Liu Avatar asked Mar 23 '17 21:03

Tommy Liu


People also ask

How do I read the last line of a file in Shell?

To look at the last few lines of a file, use the tail command. tail works the same way as head: type tail and the filename to see the last 10 lines of that file, or type tail -number filename to see the last number lines of the file.

How do I get the last line in bash?

${str##*$'\n'} will remove the longest match till \n from start of the string thus leaving only the last line in input. Show activity on this post. Then, the first line would be ${lines[0]} , and the last line would be ${lines[-1]} .

How read file line by line in shell script and store each line in a variable?

We use the read command with -r argument to read the contents without escaping the backslash character. We read the content of each line and store that in the variable line and inside the while loop we echo with a formatted -e argument to use special characters like \n and print the contents of the line variable.


1 Answers

tag=$( tail -n 1 history.txt )

like image 132
eftshift0 Avatar answered Sep 28 '22 11:09

eftshift0