Search code examples
unixputtycsh

Cshell and Awk Infinite Running


When I run the below program, I get no return, however the program still runs forever until I end it. Can some one please exoplain to me why this would happen. I am trying to get this complex awk statement to work, however, have been very unsuccessful.

The code I am using for my Cshell is (its all on one line, but I split it here to make it easier to read):

awk '{split($2,b,""); counter = 1; while (counter < 13)
{if (b[counter] == 1 && "'$cmonth'" > counter)
{{printf("%s%s%s\n", $1, "'$letter'","'$year3'")}; counter++; 
else if (b[counter] == 1 && "'$cmonth'" <= counter) 
{{printf("%s%s%s\n", $1, "'$letter'","'$year2'")}; counter++;} 
else echo "fail"}}' fileRead >> $year$month

The text file I am reading from looks like

fff 101010101010
yyy 100100100100

Here $year2 and $year3 represent counters that start from 1987 and go up 1 year for each line read. $cmonth is just a month counter from 1–12. $letter is just a ID.

The goal is for the program to read each line and print out the ID, month, and year if the position in the byte code is 1.


Solution

  • You have some mismatched curly braces, I have reformatted to one standard of indentation.

    awk '{ \
         split($2,b,""); counter = 1 \
         while (counter < 13) { \
             if (b[counter] == 1 && "'$cmonth'" > counter){ \
                 printf("%s%s%s\n", $1, "'$letter'","'$year3'") \
                 counter++ \
             } \
             else if (b[counter] == 1 && "'$cmonth'" <= counter) { \
                 printf("%s%s%s\n", $1, "'$letter'","'$year2'") \
                 counter++ \
             } \
             else print "fail" \
         }  # while \
    }' fileRead >> $year$month
    

    Also awk does'nt support echo.

    Make sure that the \ is the LAST char on the line (no space or tab chars!!!), or you'll get a syntax error.

    Else, you can 'fold' up all of the lines into one line. adding the occasional ';' as needed.

    edit

    OR you can take the previous version of this awk script (without the \ line continuation chars), put it in a file (without any of the elements outside of the ' ....' (single quotes) and call it from awk as a file. You'll also need to made so you can pass the variables cmonth, letter, year2 and any others that I've missed.

    1. save as file
    2. edit file, remove any `\' chars, change all vars like "'$letter'" to letter **
    3. call program like

    **

     awk -v letter="$letter" -v year2="$year2" -v month="$month" -f myScript  fileRead >> $year$month
    

    **

    for example

     printf("%s%s%s\n", $1, "'$letter'","'$year2'")
    

    becomes

    printf("%s%s%s\n", $1, letter,year2)
    

    IHTH.