I am trying to get a list of file names in a directory and the first line of text from each file and output each pair to a single line to be output to a .csv file.
I have tried a bunch of different methods of using head, ls, find, and grep and combinations of these but can't seem to get the results to print onto a single line. Closest I have gotten was getting them to print on separate lines.
Here is an example of the output I would need:
filename1.txt "this is the first line of text"
filename2.txt "this is the first line of text"
I'm not really concerned with having extra characters or anything in the results, as I can edit that out easily in Excel once I have them on the same line.
Any help would be greatly appreciated.
To obtain filenames and first lines for all files in the directory, try:
awk '{print FILENAME" \"" $0"\""; nextfile}' *
To obtain filenames and first lines for all files whose names start with 328, try:
awk '{print FILENAME" \"" $0"\""; nextfile}' 328*
Consider a directory with these two files:
$ cat filename1.txt
this is the first line of text
2
3
$ cat filename2.txt
this is the first line of text
b
c
Now, run our command:
$ awk '{print FILENAME" \"" $0"\""; nextfile}' *
filename1.txt "this is the first line of text"
filename2.txt "this is the first line of text"
`awk '{...}' *
This starts awk and runs the commands inside the curly braces. With the glob *, this is run for all files. The glob can be limited to, for example, 328*.txt to work on all files whose names start with 328 and end with .txt.
By default awk will read one line at a time for each file in turn.
print FILENAME" \"" $0"\""
This tells awk to print the filename followed by " followed by the first line, $0, followed by another ".
nextfile
Since we have no interest in reading the second line, this tells awk to skip to the next file.
We can save the first lines to a file like this:
$ awk '{print FILENAME" \"" $0"\""; nextfile}' *.txt >output.txt
The output.txt file looks like:
$ cat output.txt
filename1.txt "this is the first line of text"
filename2.txt "this is the first line of text"
If i rightly understand what you are asking for, this can do it
for i in *.*
do
FL=`head -1 $i`
echo "$i \"$FL\""
done
For your requirement you can try this
OP_FILE="op.csv"
>$OP_FILE
for i in 328*.*
do
FL=`head -1 $i`
echo "$i \"$FL\"" >> $OP_FILE
done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With