Search code examples
bashshellawkls

Bash: grabbing the second line and last line of output (ls -lrS) only


I am looking to get the second line and last line of what the ls -lrS command outputs. Ive been using ls -lrS | (head -2 | tail -1) && (tail -n1) But it seems to only get the first line only, and I have to press control C to stop it.

Another problem I am having is using the awk command, I wanted to just grab the file size and file name. If I were to get the correct lines (second and last) my desired output would be

files=$(ls -lrS | (head -2 | tail -1) && (tail -n1) awk '{ print "%s", $5; "%s", $8; }' )

I was hoping it would print:

1234 file.abc

12345 file2.abc


Solution

  • Using awk:

    ls -lrS | awk 'NR==2 { print; } END { print; }'
    

    It prints when the line number NR is 2 and again on the final line.

    Note: As pointed out in the comments, $0 may or may not be available in an END block depending on your awk version.