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

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.


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"
done

Using grep:

grep -m 1 '.' *.txt >output.file

grep will match any character and will exit after first match i.e. grep will output the first lines of all the input files and we are saving those in out.txt.


Using only Bash:

for f in *.txt; do <"$f" read line; printf "$line\n" >>new.txt; done
  • *.txt is expanded to the list of folders / files ending with .txt in the current working directory (since there are only files folders ending with .txt are not a concern);
  • <"$f" read line reads one line from the file path stored in f and stores it in line;
  • printf "$line\n" >>new.txt: appends the content of line to new.txt;
% cat foo.txt 
line #1 in foo
line #2 in foo
line #3 in foo

% cat bar.txt
line #1 in bar
line #2 in bar
line #3 in bar

% for f in *.txt; do <"$f" read line; printf "$line\n" >>new.txt; done

% cat new.txt 
line #1 in bar
line #1 in foo