Unix cut: Print same Field twice

ghosh'. picture ghosh'. · Sep 13, 2012 · Viewed 7.1k times · Source

Say I have file - a.csv

ram,33,professional,doc
shaym,23,salaried,eng

Now I need this output (pls dont ask me why)

ram,doc,doc,
shayam,eng,eng,

I am using cut command

cut -d',' -f1,4,4 a.csv

But the output remains

ram,doc
shyam,eng

That means cut can only print a Field just one time. I need to print the same field twice or n times. Why do I need this ? (Optional to read) Ah. It's a long story. I have a file like this

#,#,-,-
#,#,#,#,#,#,#,-
#,#,#,-

I have to covert this to

#,#,-,-,-,-,-
#,#,#,#,#,#,#,-
#,#,#,-,-,-,-

Here each '#' and '-' refers to different numerical data. Thanks.

Answer

You can't print the same field twice. cut prints a selection of fields (or characters or bytes) in order. See Combining 2 different cut outputs in a single command? and Reorder fields/characters with cut command for some very similar requests.

The right tool to use here is awk, if your CSV doesn't have quotes around fields.

awk -F , -v OFS=, '{print $1, $4, $4}'

If you don't want to use awk (why? what strange system has cut and sed but no awk?), you can use sed (still assuming that your CSV doesn't have quotes around fields). Match the first four comma-separated fields and select the ones you want in the order you want.

sed -e 's/^\([^,]*\),\([^,]*\),\([^,]*\),\([^,]*\)/\1,\4,\4/'