[bash] Command to get nth line of STDOUT

Is there any bash command that will let you get the nth line of STDOUT?

That is to say, something that would take this

$ ls -l
-rw-r--r--@ 1 root  wheel my.txt
-rw-r--r--@ 1 root  wheel files.txt
-rw-r--r--@ 1 root  wheel here.txt

and do something like

$ ls -l | magic-command 2
-rw-r--r--@ 1 root  wheel files.txt

I realize this would be bad practice when writing scripts meant to be reused, BUT when working with the shell day to day it'd be useful to me to be able to filter my STDOUT in such a way.

I also realize this would be semi-trivial command to write (buffer STDOUT, return a specific line), but I want to know if there's some standard shell command to do this that would be available without me dropping a script into place.

This question is related to bash shell sed stdout

The answer is


Hmm

sed did not work in my case. I propose:

for "odd" lines 1,3,5,7... ls |awk '0 == (NR+1) % 2'

for "even" lines 2,4,6,8 ls |awk '0 == (NR) % 2'


ls -l | head -2 | tail -1

Alternative to the nice head / tail way:

ls -al | awk 'NR==2'

or

ls -al | sed -n '2p'

Is Perl easily available to you?

$ perl -n -e 'if ($. == 7) { print; exit(0); }'

Obviously substitute whatever number you want for 7.


For the sake of completeness ;-)

shorter code

find / | awk NR==3

shorter life

find / | awk 'NR==3 {print $0; exit}'

For more completeness..

ls -l | (for ((x=0;x<2;x++)) ; do read ; done ; head -n1)

Throw away lines until you get to the second, then print out the first line after that. So, it prints the 3rd line.

If it's just the second line..

ls -l | (read; head -n1)

Put as many 'read's as necessary.


Another poster suggested

ls -l | head -2 | tail -1

but if you pipe head into tail, it looks like everything up to line N is processed twice.

Piping tail into head

ls -l | tail -n +2 | head -n1

would be more efficient?


From sed1line:

# print line number 52
sed -n '52p'                 # method 1
sed '52!d'                   # method 2
sed '52q;d'                  # method 3, efficient on large files

From awk1line:

# print line number 52
awk 'NR==52'
awk 'NR==52 {print;exit}'          # more efficient on large files

You can use awk:

ls -l | awk 'NR==2'

Update

The above code will not get what we want because of off-by-one error: the ls -l command's first line is the total line. For that, the following revised code will work:

ls -l | awk 'NR==3'

Yes, the most efficient way (as already pointed out by Jonathan Leffler) is to use sed with print & quit:

set -o pipefail                        # cf. help set
time -p ls -l | sed -n -e '2{p;q;}'    # only print the second line & quit (on Mac OS X)
echo "$?: ${PIPESTATUS[*]}"            # cf. man bash | less -p 'PIPESTATUS'

Try this sed version:

ls -l | sed '2 ! d'

It says "delete all the lines that aren't the second one".


Examples related to bash

Comparing a variable with a string python not working when redirecting from bash script Zipping a file in bash fails How do I prevent Conda from activating the base environment by default? Get first line of a shell command's output Fixing a systemd service 203/EXEC failure (no such file or directory) /bin/sh: apt-get: not found VSCode Change Default Terminal Run bash command on jenkins pipeline How to check if the docker engine and a docker container are running? How to switch Python versions in Terminal?

Examples related to shell

Comparing a variable with a string python not working when redirecting from bash script Get first line of a shell command's output How to run shell script file using nodejs? Run bash command on jenkins pipeline Way to create multiline comments in Bash? How to do multiline shell script in Ansible How to check if a file exists in a shell script How to check if an environment variable exists and get its value? Curl to return http status code along with the response docker entrypoint running bash script gets "permission denied"

Examples related to sed

Retrieve last 100 lines logs How to replace multiple patterns at once with sed? Insert multiple lines into a file after specified pattern using shell script Linux bash script to extract IP address Ansible playbook shell output remove white space from the end of line in linux bash, extract string before a colon invalid command code ., despite escaping periods, using sed RE error: illegal byte sequence on Mac OS X How to use variables in a command in sed?

Examples related to stdout

Redirect echo output in shell script to logfile Reusing output from last command in Bash Running powershell script within python script, how to make python print the powershell output while it is running Scanf/Printf double variable C Python: How to get stdout after running os.system? How to open every file in a folder Redirect all output to file using Bash on Linux? What does it mean to write to stdout in C? logger configuration to log to file and print to stdout How to get Rails.logger printing to the console/stdout when running rspec?