bashshellawk

Shell/Bash Script to reverse the text in every other column?


I'm currently trying to write a bash/shell script that pulls data from a .csv and reverses all the string values in every other column and outputs to a new csv. I have a script that grabs every other column but I'm not sure how to reverse the strings in those columns.

awk 'BEGIN{FS=","} {s=$NF; 
   for (i=1; i<=NF; i+=2) 
   printf ("%s%c", $i, i + 2 <= NF ? "," : "\n") 
}' input.csv > output.csv

Solution

  • awk to the rescue!

    $ seq 100 141 | pr -6ats, | 
      awk -F, 'function rev(x) {r=""; 
                                for(j=length(x);j;j--) r=r substr(x,j,1); 
                                return r}
               BEGIN {OFS=FS} 
                     {for(i=1;i<NF;i+=2) $i=rev($i)}1' 
    
    001,101,201,103,401,105
    601,107,801,109,011,111
    211,113,411,115,611,117
    811,119,021,121,221,123
    421,125,621,127,821,129
    031,131,231,133,431,135
    631,137,831,139,041,141