# How to truncate only given column length?

INPUT:

``````a@notebook:~\$ cat in.csv
'YYZ814384'^'ASfdEtRiuognfnseaFREQTzKb   aSFfdsaADSFSA  adsFdsa34 34 ASFfsas  saftrzj etrzrasdfasffasf safs'^'foooobaaar'^'ZZZ'^'..... and so on, further columns
``````

OUTPUT:

``````a@notebook:~\$ cat in.csv | SOMEMAGIC
'XYZ843141'^'ASDFSAFXYVFSHGDSDg s'^'BAAAR'^'YYY'^'..... and so on, further columns
'YYZ814384'^'ASfdEtRiuognfnseaFRE'^'foooobaaar'^'ZZZ'^'..... and so on, further columns
``````

My question: If:

``````'^'
``````

is the separator, then how can SOMEMAGIC (an awk/sed??) truncate the second column to given length? Example: 20 chars max, from this:

``````ASDFSAFXYVFSHGDSDg sdGDS  dsGDSgfa assfd faSDFAS saDFSAFD adFSA343fa sdfSADF
``````

to this:

``````ASDFSAFXYVFSHGDSDg s
``````

and preserve all the other things :\

``````> awk -v OFS="'^'" -F"'\\\\^'" '{if(length(\$2)>20) \$2=substr(\$2,1,20); print;}' file
'XYZ843141'^'ASDFSAFXYVFSHGDSDg s'^'BAAAR'^'YYY'^'..... and so on, further columns
'YYZ814384'^'ASfdEtRiuognfnseaFRE'^'foooobaaar'^'ZZZ'^'..... and so on, further columns
``````

Here is a simple sed example to get only 20 caracters from our string:

``````\$ str = "ASDFSAFXYVFSHGDSDg sdGDS  dsGDSgfa assfd faSDFAS saDFSAFD adFSA343fa sdfSADF"

\$ echo \$str | sed -e 's/^\(.\{20\}\).*/\1/'
ASDFSAFXYVFSHGDSDg s
``````

Or with cut command:

``````\$ echo \$str | cut -c 1-20
``````

``````\$ echo \$str | awk -F "^" '{print \$1,\$2}'
'XYZ843141' 'ASDFSAFXYVFSHGDSDg s'
``````
• now we only have to do this to the second column of a string, as in the example :\ – evachristine Jul 1 '14 at 13:30
• simple and perfect thanks! `cat file.txt |cut -c 1-\$(tput cols)` – Aquarius Power Mar 22 '15 at 19:46

You may try this:

``````paste -d^ <(cut -f1 -d^ in.csv) \
<(cut -f2 -d^ in.csv | sed -e 's/^\(.\{21\}\).*/\1'\''/')\
<(cut -f3- -d^ in.csv)
``````

However this will fail if there is `^` in some of the fields.