To replace header name

Hi,

i am having below csv file with header names, i need to change the header with appending a string

test.csv

h1,h2,h3,h4

Ouptut

hi_h1,hi_h2,hi_h3,hi_h4

I have tried below but this will take time if i have 100 headers. Is there a way to simplify this

sed -e 's#h1#'hi_h1'#g'  -e 's#h2#'hi_h2'#g' test.csv

Without seeing the rest of the file I am guessing. You can try this or maybe change it to your needs:

$ echo "h1,h2,h3,h4" | sed 's/h[0-9]\+/hi_&/g'
hi_h1,hi_h2,hi_h3,hi_h4

When you mention "headers", you talk of first lines of a text file? Try this small amendment of zaxxon's proposal:

sed '1s/h[0-9]\+/hi_&/g' test.csv

More generic and untested...

awk  -v add="hi_"  -F, 'NR==1{for(i=1;i<=NF;i++) $i=add $i}1' OFS=","  file

Hello rohit_shinez,

Could you please try following too and let me know if this helps.(Considering only headers you need to change this which will be off course first line of Input_file)

awk 'NR==1{gsub(/h[0-9]+/,"hi_&",$0);print;next} 1'    Input_file

Thanks,
R. Singh

Independent of name of header:

sed '1s/^/hi_/; 1s/,/,hi_/g' test.csv

GNU sed (-r), BSD sed (-E):

sed -r '1s/(^|,)/&hi_/g' test.csv
1 Like