LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   [awk] NR problem (https://www.linuxquestions.org/questions/programming-9/%5Bawk%5D-nr-problem-825728/)

dhodho 08-12-2010 02:56 AM

[awk] NR problem
 
I have 2 cases. If I did
Code:

awk '{if(NR==27)$2="NaN";print NR"\t"$2}' input > output
I can get result. It means for NR=27, the second column in output file will be NaN

But I modified the command
Code:

for nn in 27
do
awk '{if(NR=="'"${nn}"'")$2="NaN";print NR"\t"$2}' input > output
done

I didn't get the result the same as the first way. It means there is no change for the second column of NR=27.

Are there some tricks to deal with it?
Any kind help is greatly thanked.

grail 08-12-2010 03:56 AM

Well not sure why you are doing the for loop outside the awk seeing it has one of its own, but if we stay with this format, try setting an awk variable:
Code:

for nn in 27
do
    awk -vn=$nn '{if(NR==n)$2="NaN";print NR"\t"$2}' input > output
done

Also I would submit an alternative to the awk, but of course each to their own:
Code:

for nn in 27
do
    awk -vn=$nn 'NR == n{$2="NaN"}1' input > output
done

This of course takes out your test print

dhodho 08-12-2010 10:03 PM

I must replace randomly some NR with NaN.
I tried your code, but there is no change.
Below is my complete code
Code:

for nn in 27 134 181 191 194 196
do
    awk -vn=$nn 'NR == n{$2="NaN"}1' input > output
done


dhodho 08-13-2010 12:43 AM

I think my title is no so clear. I move my problem to new thread.
Sorry for this inconvenience.

grail 08-13-2010 04:31 AM

Please mark this one as SOLVED then.


All times are GMT -5. The time now is 07:23 PM.