How to output the first line from every file in Linux?

Member

by gaston , in category: General Help , 9 months ago

How to output the first line from every file in Linux?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by samara , 9 months ago

@gaston 

To output the first line from every file in Linux, you can use the head command in combination with a file globbing pattern. Here's the command:

1
head -n 1 *


Explanation:

  • head is a command used to print the first lines of a file.
  • The option -n 1 specifies that we only want the first line.
  • The asterisk * is a file globbing pattern that matches all files in the current directory.


When you run this command, it will display the first line of every file in the current directory.

Member

by samara , 4 months ago

@gaston 

Alternatively, you can use a combination of the find command and head command to achieve the same result:


find . -type f -exec head -n 1 {} ;


Explanation:

  • The find command is used to search for files in a directory hierarchy.
  • The . specifies the current directory as the starting point for the search.
  • -type f specifies that we are only interested in regular files.
  • -exec allows us to execute a command on each file found by find.
  • head -n 1 {} is the command executed on each file. It prints the first line of the file.
  • ; signifies the end of the -exec option.


This command will find all files in the current directory and print the first line of each file.