Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

unix

pipe

I have been trying to get the head utility to display all but the last line of standard input. The actual code that I needed is something along the lines of cat myfile.txt | head -n $(($(wc -l)-1)). But that didn't work. I'm doing this on Darwin/OS X which doesn't have the nice semantics of head -n -1 that would have gotten me similar output.

None of these variations work either.

cat myfile.txt | head -n $(wc -l | sed -E -e 's/\s//g') echo "hello" | head -n $(wc -l | sed -E -e 's/\s//g') 

I tested out more variations and in particular found this to work:

cat <<EOF | echo $(($(wc -l)-1)) >Hola >Raul >Como Esta >Bueno? >EOF 3 

Here's something simpler that also works.

echo "hello world" | echo $(($(wc -w)+10)) 

This one understandably gives me an illegal line count error. But it at least tells me that the head program is not consuming the standard input before passing stuff on to the subshell/command substitution, a remote possibility, but one that I wanted to rule out anyway.

echo "hello" | head -n $(cat && echo 1) 

What explains the behavior of head and wc and their interaction through subshells here? Thanks for your help.

like image 430
gkb0986 Avatar asked Aug 08 '13 13:08

gkb0986


People also ask

How do I display the last line of a file?

Use the tail command to write the file specified by the File parameter to standard output beginning at a specified point. This displays the last 10 lines of the accounts file. The tail command continues to display lines as they are added to the accounts file.

Which is the best command to view the last lines of a file?

To look at the last few lines of a file, use the tail command. tail works the same way as head: type tail and the filename to see the last 10 lines of that file, or type tail -number filename to see the last number lines of the file.

Which command is used to print the last N lines of a file?

tail [OPTION]... [ Tail is a command which prints the last few number of lines (10 lines by default) of a certain file, then terminates.

How many lines from the file are command head displayed by default?

The Linux head command prints the first lines of one or more files (or piped data) to standard output. By default, it shows the first 10 lines.


1 Answers

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

like image 70
dunc123 Avatar answered Oct 06 '22 00:10

dunc123