-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
  • 77,979
  • 13
  • 71
  • 125
Omar
  • 81
  • 6

3 Answers3

2

Use tail ;)

line=$(tail -n 1 input_file)
echo $line
Benjamin W.
  • 38,596
  • 16
  • 96
  • 104
Gnik
  • 204
  • 2
  • 10
1

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
  • 117,272
  • 11
  • 49
  • 86
0

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.

Tiw
  • 5,078
  • 13
  • 24
  • 33