Storing lines of a file in a variable

i want to store the output of 'tail -5000 file' to a variable.

If i want to access the contents of that variable, it becomes kinda difficult because when the data is stored in the variable, everything is mushed together. you dont know where a line begins or ends.

so my question is, how can i store the results of "tail -5000 file" into a variable and be able to access the contents of that variable as though it is an actual file?

It does not get mushed, the only thing is that you must use quotes around the variable when referencing it:

var=$(tail -5000 file)
printf "%s\n" "$var" 
1 Like

It wont if the echoed variable is double quoted...

VAR=$(tail -5000 file)
echo $VAR     # everything is mushed together
echo "$VAR"   # preserves newlines so nothing is mushed together
1 Like

Please bear in mind that the buffer space for tail -n is limited.
Make sure that the command works on your computer.
On my computer it does not work because the buffer space in tail -n is too small: see man tail :

ls -ald bigfile
-rw-r--r--   1 root       sys        606832653 Jun 25  2010 bigfile
tail -5000 bigfile | wc -l
187

@SkySmart
For this and future postings, please post what Operating System and version you have and what Shell you are using.

1 Like