Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Expand
titleAnswer...

Just entering the cat command with no arguments appears to "hang" – that is, nothing happens and you don't see the command prompt (just Ctrl-c to get it back).

Reading the man page for cat says this:

Code Block
languagebash
NAME
    cat - concatenate files and print on the standard output
SYNOPSIS
    cat [OPTION]... [FILE]...
DESCRIPTION
    Concatenate FILE(s) to standard output.
    With no FILE, or when FILE is -, read standard input.

The SYNOPSYS says in addition to one of more optional options to cat ( [OPTION}... ) arguments to cat are also optional ( [FILE]... ).

Since there was no FILE provided, cat reads from standard input – but there's no data there either, so it just sits and waits for some to appear.

...

With no options, head shows the first 10 lines of its input and tail shows the last 10 lines. You can use the -n option followed by a number to specify how many lines lines to view, or just put the number you want after a dash (e.g. -5 for 5 lines or -1 for 1 line).

...

But what if you want to see lines in the middle of a file? Here's where a special feature of tail comes in handy. If you use tail and put a plus sign (+) in front of the number (with or without the -n option), tail will start its output at that line.

Let's pipe line-numbered output from cat to tail to see how this works:. Note we use cat -n to provide input with line numbers because neither head nor tail has line numbering options.

Code Block
languagebash
cat -n haiku.txt | tail -n 75   # display the last 75 lines of haiku.txt
cat -n haiku.txt | tail -n +75  # display text in haiku.txt starting at 
line  7 cat -n haiku.txt | tail +10    # display text in haiku.txt starting at line 10              line 5
cat -n haiku.txt | tail +6     # display text in haiku.txt starting at 
                                 line 6

When you use the tail -n +<integer> syntax it will display all output starting from that line to the end of its input. So to view only a few lines starting at a specified line number, pipe the output to head:

Code Block
languagebash
# display 2 lines of haiku.txt starting at line 9
cat -n haiku.txt | tail -n +9 | head -2
cat -n haiku.txt | tail +9 | head -n 2

cat -n haiku.txt | head -10 | tail -2

...

Expand
titleAnswer...

There are three 3-line stanzas in haiku.txt. The middle stanza is lines 5-7.

Code Block
languagebash
cat -n haiku.txt | tail -n +5 | head -n 3
cat -n haiku.txt | tail +5 | head -3

cat -n haiku.txt | head -7 | tail -3


...