I was trying to write a shell script wherein I can extract the headers and also the filename from a list of files in a given directory.

For example: ABC_TESTFILE1.csv contains headers like


ABC_TESTFILE2.csv contains headers like


I want output text file as:


I was trying my luck as:


# Go to where the files are located

for filepath in $filedir
 #echo "Processing $filename"
 # do something on $f
 var_head=$(head -n 1 basename "$filepath" )
 echo "$var_head"
done; > test.txt
  • 1
    You question contains a headline "!/bin/bash" without any text in that section. Something seems to be messed up here. Please fix. – Martin Konrad May 16 at 16:51
  • have corrected that. Thanks – vikrant rana May 16 at 16:53
  • 1
    Beware: on the last line of your script that ";" means that the >test.txt is a separate command, so you are not writing into the file. – meuh May 16 at 17:05

You could use printf to format the output of basename and head:

for file in /home/vikrant_singh_rana/AAA_USP/Combined-Files/*.csv; do
  printf '%s,%s\n' "$(basename "$file" ".csv")" "$(head -n1 "$file")"
done >test.txt
| improve this answer | |

Using AWK:

awk 'NR==1 {print FILENAME "," $0}' *.csv

will list all the files with a .csv extension containing at least one line, with the first line.

| improve this answer | |
path=(`ls -d /tmp/*.csv`)
        for file in "${path[@]}"; do
            head_line=`head -n1 $file`
            file_no_extension=`basename $file | sed 's/\..*//'`
            echo "$file_no_extension""$head_line"

Make sure that path its an array:

[root@mole tmp]# set | grep ^path=
path=([0]="/tmp/ABC_TESTFILE1.csv" [1]="/tmp/ABC_TESTFILE2.csv")
| improve this answer | |

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.