Ubuntu – How to select the first line from each file in a directory and print it into a new text file

command linetext processing

I have a directory with several .txt files.

From each of these files, I want to select the first line and print it into a new .txt file (to get a list of all the first lines).

I tried it with the awk and sed commands and combined it with a loop, but without success.

Best Answer

Use head:

head -n1 -q *.txt > new-file
  • -n1 tells head to extract the first line only.
  • -q tells head not to print the filename.

On OS X (and probably on some other *nix variants) the -q option is not supported by head. You need to remove the filenames yourself, e.g.

head -n1 *.txt | grep -v '==> ' > new-file

This only works if you know the output shouldn't contain the ==>  string. To be absolutely sure, use a loop (which will be much slower than running head just once):

for file in *.txt ; do
    head -n1 "$file"