bashshellterminalhead

How to print the first line of multiple files?


I am on Mac Os 10.14.6 and have a directory that contains hundreds of text files.

In the terminal, I would like to display a list of the first line of every file. How can I do this?



Steps I have tried

Googling around, I think the solution is to use a command called head. This is the command I have tried: head -n 1 *

However, it produces output like this:

==> Minutes.txt <==
Minutes of the meeting

==> Daily Report.txt <==
Daily Report for Feb

==> Important incidents.txt <==
Incidents that happened yesterday

I don’t want the File 1.text headings. I just want it to be a list like this:

Minutes of the meeting
Daily Report for Feb
Incidents that happened yesterday

According to this page, you can use any one of the following commands to remove the headers:

-q, --quiet, --silent

So I revised my command as follows:

head -n1 -q *

But it produces the following error message:

head: illegal option -- q
usage: head [-n lines | -c bytes] [file ...]

How can I display a list of the first line of every file without the header. The solution doesn't have to use head although from my research, that seems to be the best approach.


Solution

  • I'm guessing your version of head doesn't support the -q option; what does man head (run on your Mac) show?

    A small awk solution:

    awk '{ print ; nextfile }' *
    

    As a file is processed the first line is printed, then we skip to the next file; net result is that we only print the first line of each file.

    Keep in mind this could generate some odd results depending on what matches * ... binary files? directories?