Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first line of a shell command's output

Tags:

linux

bash

shell

While trying to read the version number of vim, I get a lot additional lines which I need to ignore. I tried to read the manual of head and tried the following command:

vim --version | head -n 1

I want to know if this is the correct approach?

like image 618
john doe Avatar asked Oct 16 '22 10:10

john doe


People also ask

How do you find the first line of output?

Yes, that is one way to get the first line of output from a command. There are many other ways to capture the first line too, including sed 1q (quit after first line), sed -n 1p (only print first line, but read everything), awk 'FNR == 1' (only print first line, but again, read everything) etc.

How do I read the first line of a file in shell?

Just echo the first list of your source file into your target file. For which head -n 1 source. txt > target.

How do I make the first line of a file read only in Linux?

To look at the first few lines of a file, type head filename, where filename is the name of the file you want to look at, and then press <Enter>. By default, head shows you the first 10 lines of a file. You can change this by typing head -number filename, where number is the number of lines you want to see.


2 Answers

Yes, that is one way to get the first line of output from a command.

If the command outputs anything to standard error that you would like to capture in the same manner, you need to redirect the standard error of the command to the standard output stream:

utility 2>&1 | head -n 1

There are many other ways to capture the first line too, including sed 1q (quit after first line), sed -n 1p (only print first line, but read everything), awk 'FNR == 1' (only print first line, but again, read everything) etc.

like image 247
Kusalananda Avatar answered Oct 17 '22 22:10

Kusalananda


I would use:

awk 'FNR <= 1' file_*.txt

As @Kusalananda points out there are many ways to capture the first line in command line but using the head -n 1 may not be the best option when using wildcards since it will print additional info. Changing 'FNR == i' to 'FNR <= i' allows to obtain the first i lines.

For example, if you have n files named file_1.txt, ... file_n.txt:

awk 'FNR <= 1' file_*.txt

hello
...
bye

But with head wildcards print the name of the file:

head -1 file_*.txt

==> file_1.csv <==
hello
...
==> file_n.csv <==
bye
like image 6
alemol Avatar answered Oct 17 '22 23:10

alemol