-1

I am working on a tool project. I need to grab the last line from a file & assign into a variable. This is what I have tried:

line=$(head -n $NF input_file)
echo $line

Maybe I could read the file in reverse then use

line=$(head -n $1 input_file)
echo $line

Any ideas are welcome.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Omar
  • 81
  • 1
  • 7

3 Answers3

2

Use tail ;)

line=$(tail -n 1 input_file)
echo $line
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Gnik
  • 204
  • 3
  • 10
2

Combination of tac and awk here. Benefit in this approach could be we need NOT to read complete Input_file in it.

tac Input_file | awk '{print;exit}'
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
1

With sed or awk :

sed -n '$p' file
sed '$!d' file
awk 'END{print}' file

However, tail is still the right tool to do the job.

Til
  • 5,150
  • 13
  • 26
  • 34