2

I need to split a csv string into an array, and cut the content of its elements to a lngth or 300 if the element's content exceed the 300 characters. I'm very close to it but for some reason that i cant figure out, this is not working:

awk '{split($0,fields,",") 
 for(field in fields)
    if(length(fields[field]) >300){
     gsub(fields[field],substr(fields[field],0,300),$0)
   } print 
 }' file_in.csv > file_out

I can see it when i run this test:

awk '{split($0,fields,","); for(field in fields) if(length(fields[field]) >=301){print fields[field]} }' file_out

This is still prnting some fields Any idea whats wrong with my awk?

4
  • It would help both you and us if you didn't use an inline script for this. It's not trivial enough. I'd save it to a file, put some newlines into it, and come back Commented Feb 27, 2014 at 12:16
  • Avoid to use gsub in such a case, because characters ? and ` are interpreted as special characters (resp. wildcard and escape next one). Instead call only substr`. Commented Feb 27, 2014 at 12:42
  • @Bentoy13 you mean sub() , not substr() Commented Feb 27, 2014 at 12:44
  • 2
    @JBoy Not really, you don't need to call gsub or sub... substr is enough to get the correct output. Commented Feb 27, 2014 at 12:49

2 Answers 2

2

You can use this awk to trim fields > 300:

awk 'BEGIN{FS=OFS=","} 
     {for (i=1; i<=NF; i++) if (length($i)>300) $i=substr($i,1,300)}
     1' file.csv
Sign up to request clarification or add additional context in comments.

Comments

0

I've changed 300 by 3 to do it readable:

$echo "Hello,World"| awk '{split($0, fields,",");str=""; for (field in fields){str = str substr(fields[field],0,3) ","}; print substr(str,0,length(str)-1)}'
Hel,wor

Line is a little long, splitted is:

awk '{split($0, fields,",");
      str="";
      for (field in fields){
         str = str substr(fields[field],0,3) ","
      };
      print substr(str,0,length(str)-1)}'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.