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.
5 Answers
Use head:
head -n1 -q *.txt > new-file -n1tellsheadto extract the first line only.-qtells 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 4Using 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 *.txtis expanded to the list of folders / files ending with.txtin the current working directory (since there are only files folders ending with.txtare not a concern);<"$f" read linereads one line from the file path stored infand stores it inline;printf "$line\n" >>new.txt: appends the content oflinetonew.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 4You have tried it with awk, here is a awk version
awk 'FNR==1 {print} {nextfile}' *.txt > out Another approach with AWK is to tell AWK to print, but then immediately go to next file
tmp:$ touch file1 file2 file3 tmp:$ printf "Line 1 \n Line 2" | tee file1 file2 file3 Line 1 Line 2 tmp:$ awk '{print;nextfile}' file1 file2 file3 Line 1 Line 1 Line 1 sed also allows printing of specific lines . Here I've combined that with find
tmp:$ find . -name "file*" -exec sed -n '1p' {} \; Line 1 Line 1 Line 1 And perl:
tmp:$ find . -name "file*" -exec perl -ne 'print if 1..1' {} \; Line 1 Line 1 Line 1 And last but not least , grep
tmp:$ grep -n 1 file1 file2 file3 file1:1:Line 1 file2:1:Line 1 file3:1:Line 1 Saving everything to a single file is just a matter of appending > outputFile.txt at the end of these commands.