Harness the Combinatoric Power of Command-Line Tools and Utilities

../Tutorials

Reading a Single Line from a File from the Command Line Interface

Bash scripts

Published December 11, 2020 and last verified on March 9, 2024

When you get an error report from a linter, interpreter, or compiler, you’ll get results that tell you to look at a certain line number. You can then jump to that line in your editor or IDE. But sometimes it’s nice to be able to just look at a single line in a file.

There are a number of ways to do this, but the shortest and fastest way (read: least amount of typing) is with the sed command, and its -n option:

sed -n [line_number]p filename.txt

For example, to read the fifth line from a file called index.html, use this command:

sed -n 5p index.html

You can also use this to pipe data in. To view the second line of a long directory listing, you can do this:

ls -alh | sed -n 5p

As I mentioned, there are other solutions for this, but this is the one I settled on because it’s less typing. However, you can reduce the typing even more if you use a shell function.

If you’re using Bash, you can add a function to your ~/.bash_rc file on Linux/WSL or to ~/.bash_profile on macOS that calls sed:

catln() {
  sed -n ${1}p ${2}
}

This function accepts two arguments: a line number and a file. To read line 5 of index.html, you call the function like this:

catln 5 index.html

To use this, add this function to your appropriate profile file and then open a new terminal so it loads in or use source to load your configuration.

If you want to be able to pipe text into the function like you could with sed, you’ll have to modify the function to read from standard input if you don’t see the second argument. Here’s how you’d do it:

catln() {
  num=$1
  input=$2
  if [ -z "$input" ]; then
    sed -n ${num}p </dev/stdin
  else
    sed -n ${num}p $input
  fi
}

For clarity, create two local variables: num to hold the number of lines, and input to hold the input. Then check to see if the input was supplied. If it wasn’t, then call sed and pass in /dev/stdin instead. Otherwise, pass the file.

Update the function in your profile file, source it or open a new terminal, and use the function with a pipe:

ls -alh | catln 2

You’ll see the second line of your directory listing.

So there you have it; a quick way to display a line from a file.