Insert a header record (tab delimited) in multiple files

Hi Forum.

I'm struggling to find a solution for the following issue.

I have multiple files a1.txt, a2.txt, a3.txt, etc. and I would like to insert a tab-delimited header record at the beginning of each of the files.

This is my code so far but it's not working as expected.

for i in a*.txt; { awk 'BEGIN{print "CIF,"\t",Status,"\t",FirstName,"\t",LastName,"\t",BirthDate,"\t",Address,"\t",City,"\t",Province,"\t",Country,"\t",occupation,"\t",ClientSinceDate TotalBalance"}1' $i > $i.tmp; mv $i.tmp $i; }

Thank you for your help

Using awk inside a for loop is an overkill for this task. You can use a command grouping construct for this task:

#!/bin/ksh

for i in a*.txt
do
 {
  print "CIF,"\t",Status,"\t",FirstName,"\t",LastName,"\t",BirthDate,"\t",Address,"\t",City,"\t",Province,"\t",Country,"\t",occupation,"\t",ClientSinceDate TotalBalance"
  cat "$i"
 } > "${i}.tmp"
 mv "${i}.tmp" "$i"
done

By the way I noticed that you missed do and done in your for loop.

And also the \t must be in a quoted string, otherwise the shell prints a literal t.

print "CIF\tStatus\tFirstname\tLastname"

or

printf "%s\t" CIF Status Firstname Lastname
printf "\n"
1 Like