Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Awk to Print every character as its own column?

Tags:

awk

I am in need of reorganizing a large CSV file. The first column, which is currently a 6 digit number needs to be split up, using commas as the field separator.

For example, I need this:

022250,10:50 AM,274,22,50
022255,11:55 AM,275,22,55

turned into this:

0,2,2,2,5,0,10:50 AM,274,22,50
0,2,2,2,5,5,11:55 AM,275,22,55

Let me know what you think!

Thanks!

like image 761
wizkid84 Avatar asked Jan 23 '23 07:01

wizkid84


2 Answers

It's a lot shorter in perl:

perl -F, -ane '$,=","; print split("",$F[0]), @F[1..$#F]' <file>

Since you don't know perl, a quick explanation. -F, indicates the input field separator is the comma (like awk). -a activates auto-split (into the array @F), -n implicitly wraps the code in a while (<>) { ... } loop, which reads input line-by-line. -e indicates the next argument is the script to run. $, is the output field separator (it gets set iteration of the loop this way, but oh well). split has obvious purpose, and you can see how the array is indexed/sliced. print, when lists as arguments like this, uses the output field separator and prints all their fields.

In awk:

awk -F, '{n=split($1,a,""); for (i=1;i<=n;i++) {printf("%s,",a[i])}; for (i=2;i<NF;i++) {printf("%s,",$i)}; print $NF}' <file>
like image 184
Cascabel Avatar answered Jan 29 '23 12:01

Cascabel


I think this might work. The split function (at least in the version I am running) splits the value into individual characters if the third parameter is an empty string.

  BEGIN{ FS="," }
  {
     n = split( $1, a, "" );
     for ( i = 1; i <= n; i++ )
        printf("%s,", a[i] );

     sep = "";
     for ( i = 2; i <= NF; i++ )
        {
        printf( "%s%s", sep, $i );
        sep = ",";
        }
     printf("\n");
  }
like image 33
Mark Wilkins Avatar answered Jan 29 '23 13:01

Mark Wilkins