0

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

C1,C2,C3

ABC_TESTFILE2.csv contains headers like

C1,C4,C5

I want output text file as:

ABC_TESTFILE1,C1,C2,C3
ABC_TESTFILE2,C1,C4,C5

I was trying my luck as:

#!/bin/bash

# Go to where the files are located
filedir=/home/vikrant_singh_rana/AAA_USP/Combined-Files/*

for filepath in $filedir
do
 #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
1

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 | |
2

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

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.