Unix cut: Print same Field twice

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/'

using perl:

perl -F, -ane 'chomp($F[3]);$a=$F[0].",".$F[3].",".$F[3];print $a."\n"' your_file

using sed:

sed 's/\([^,]*\),.*,\(.*\)/\1,\2,\2/g' your_file

$ sed 's/,.*,/,/; s/\(,.*\)/\1\1,/' a.csv
ram,doc,doc,
shaym,eng,eng,

What this does:

  • Replace everything between the first and last comma with just a comma
  • Repeat the last ",something" part and tack on a comma. Voilà!

Assumptions made:

  • You want the first field, then twice the last field
  • No escaped commas within the first and last fields

Why do you need exactly this output? :-)

Tags:

Unix

Shell

Sed

Cut