2

I am trying to create files using AWK with in a for loop but getting empty file. It looks like AWK is not getting executed. Can you please advise, what is incorrect here?

I have a file $LOG/order_"$id".txt which has some lines between 2 strings CUT:1 and CUT2 etc.. I just need these lines in separate files so I wrote this for loop.

for (( i=1; i<=$CNTLN; i++ ))
do
    j=`expr $i - 1`
    /usr/bin/awk '/CUT:$j/, /CUT:$i/' $LOG/order_"$id".txt >  $LOG/order_"$id"_"$i".txt
done

This generate blank file however if I copy and past this command on shell, it works.

Please advise.

1
  • 2
    Shot in the dark: did you try replacing the simple quote by double quote around the "/CUT:$j...." part? Commented Apr 26, 2012 at 2:58

1 Answer 1

2

Your quoting is correct, however you should use variable passing instead of trying to embed shell variables within the AWK script.

for (( i=1; i<=CNTLN; i++ ))
do
    (( j = i - 1 ))
    /usr/bin/awk -v i="$i" -v j="$j" '$0 ~ "CUT:" j, $0 ~ "CUT:" i' "$LOG/order_$id.txt" >  "$LOG/order_${id}_$i.txt"
done

When using AWK variables, you have to use the tilde match operator instead of the slash-delimited form.

You don't say which shell you're using, but based on the for statement, I'd guess Bash, Korn or Z shell. If it's one of those, then you can do integer arithmetic as I've shown without using the external expr utility. In the case of ksh or zsh, you can do float math, too.

You could eliminate the line that calculates j and include it in the for statement.

for (( i=1, j=0, i<=CNTLN; i++, j++ ))

In a couple of places you use all-caps variable names. I recommend making a habit of not doing this in order to avoid name collisions with shell or environment variables. It's not an issue in this specific case, but it's a good habit to be in.

Actually, now that I think about it. The shell loop could be eliminated and the whole thing written in AWK.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.