Getting head to display all but the last line of a file: command substitution and standard I/O redirection Getting head to display all but the last line of a file: command substitution and standard I/O redirection unix unix

Getting head to display all but the last line of a file: command substitution and standard I/O redirection


head -n -1 will give you all except the last line of its input.


head is the wrong tool. If you want to see all but the last line, use:

sed \$d

The reason that

# Sample of incorrect code:echo "hello" | head -n $(wc -l | sed -E -e 's/\s//g')

fails is that wc consumes all of the input and there is nothing left for head to see. wc inherits its stdin from the subshell in which it is running, which is reading from the output of the echo. Once it consumes the input, it returns and then head tries to read the data...but it is all gone. If you want to read the input twice, the data will have to be saved somewhere.


Using sed:

sed '$d' filename

will delete the last line of the file.

$ seq 1 10 | sed '$d' 123456789