HattrickNZ
HattrickNZ

Reputation: 4663

bash + getting the headers from a file and numbering them

This gets all the headers in a file

$head -n 1 basicFile.csv | tr ',' '\n'
    header1
    header2
    header3
    header4
    header5
    header6
    header7
    header8
    header9
    header10

what I want is to add the header number to the left to get something like:

1:header1
...
10:header10

How do I do this?

Upvotes: 1

Views: 155

Answers (4)

gboffi
gboffi

Reputation: 25093

It depends, just the shell or is awk good enough?

% cat count_headers
cnt=1 ; head -n 1 "$1" | tr ',' '\n' | while read header ; do 
   printf "%d:%s\n" $cnt "$header"
   cnt=$(($cnt+1))
done
% sh count_headers basicFile.csv
1:...
...
% awk -F, 'NR==1 {for(i=1;i<=NF;i++) print i ":" $i}' basicFile.csv
1:...
...
% 

Upvotes: 0

whereswalden
whereswalden

Reputation: 4969

There might be a shorter way of doing it with awk, but this works:

oldIFS=$IFS   
IFS=','
i=1
for header in $(head -n 1 basicFile.cs); do
  echo ${i}:$header
  ((i++))
done
IFS=$oldIFS

Upvotes: 1

glenn jackman
glenn jackman

Reputation: 247082

head -n 1 basicFile.csv | tr ',' '\n' | cat -n

Not exactly the output you specified, but pretty close.

Upvotes: 3

Hunter McMillen
Hunter McMillen

Reputation: 61540

You can just use a simple counter and for loop:

COUNTER=1
for h in $(head -n 1 basicFile.csv | tr ',' '\n')
do
   printf "%d:%s\n" "$COUNTER" "$h"
   (( COUNTER++ ))
done

Upvotes: 0

Related Questions