cancel
Showing results for 
Search instead for 
Did you mean: 

generalizing fields for Awk

SOLVED
Go to solution
parmy_4
Occasional Contributor

generalizing fields for Awk

Hi,
I have a file that has about 16 columns delimited by comma(","). I need to append only the first two columns by hyphen("-"). For that I am doing some thing like below

awk -F, 'OFS=","{print $1"-"$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16}' my_file

Is there any way of generalising the columns from 3 to 16??

I am expecting some thing like
awk -F, 'OFS=","{print $1"-"$2,$3-$16}' my_file

Is this possible?

Please kindly help.
Thanks and Regards,
-Parmy
7 REPLIES
Simon Hargrave
Honored Contributor

Re: generalizing fields for Awk

Not in awk, you have to use a for loop, eg: -

awk '{ printf $1"-" ; for(i=2; i<=NF; i++) { printf ","$i } ; printf "\n" }' my_file
Hein van den Heuvel
Honored Contributor
Solution

Re: generalizing fields for Awk

You could just print $1, that hyphen, and then the substring from the line ($0) starting after $1 and the space.

awk '{ print $1 "-" substr($0,length($1)+2) }' my_file

Hein.
Rodney Hills
Honored Contributor

Re: generalizing fields for Awk

How about using perl and just replace the first "," with a "-".

perl -p -e 's/,/-/' my_file

HTH

-- Rod Hills
There be dragons...
Jean-Luc Oudart
Honored Contributor

Re: generalizing fields for Awk

Hi,

you just can use sed command to substitute the 1st comma :

cat | sed -e "s/\,/\-/" >

Regards
Jean-Luc
fiat lux
Muthukumar_5
Honored Contributor

Re: generalizing fields for Awk

We can do this as,

echo "a,b,c,d,e,f,g,h,i,j,k,l,i,j,k,l" | awk -F , '{ printf $1"-"
> for ( i=2; i> printf $i ","
> } END { printf $NF }'

output:
a-b,c,d,e,f,g,h,i,j,k,l,i,j,k,l

Or just easy as,
echo "a,b,c,d,e,f,g,h,i,j,k,l,i,j,k,l" | sed -e 's/,/-/1'

It will change first occurence of , and change it to -

Regards
Muthu
Easy to suggest when don't know about the problem!
curt larson_1
Honored Contributor

Re: generalizing fields for Awk

no there isn't any syntax for specifing a range of fields within awk.

but if your data is already comma delimited,
all you need to do is change the first comma

awk '{sub(",","-");print $0;}'

or using sed

sed -e 's/,/-/'

and you already have a perl example


parmy_4
Occasional Contributor

Re: generalizing fields for Awk

Guys,
Thanks a lot for your time helping me to know about generalising. I am impressed by all your replies and thanks again.

Regards,
Parmy