Glam Prestige Journal

Bright entertainment trends with youth appeal.

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.

0

5 Answers

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
4

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.

1

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
4

You 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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy