2

My data file is

sdfsdfsdf
1 0.5000 0.5000 0.5000 8 7 90 135  90 135 1 
2 0.5000 0.5000 0.0000 8 7 90 -45  90 -45 1 
3 0.0000 0.5000 0.5000 8 7 90 225  90 225 1 
4 0.5000 0.0000 0.5000 8 7 90 45   90 45  1 
sdfsdfsdf
sdfsdfsdfsdfsdfsdfsdf

and I want to change 7th and 9th column of 2~5 lines, so the result to look like

sdfsdfsdf
1 0.5000 0.5000 0.5000 8 7 60 135  60 135 1 
2 0.5000 0.5000 0.0000 8 7 60 -45  60 -45 1 
3 0.0000 0.5000 0.5000 8 7 60 225  60 225 1 
4 0.5000 0.0000 0.5000 8 7 60 45   60 45  1 
sdfsdfsdf
sdfsdfsdfsdfsdfsdfsdf

How do I this with sed or awk? I tried

awk 'NR>=2&&NR<=5{$7="60"}' input.dat > tmp && mv tmp input.dat

but this doesn't work

2 Answers 2

1

Try:

awk 'FNR==2,FNR==5{$7=$9=60};1' input.dat > tmp
2
  • Can you please tell me what is the 1 for?
    – venki421
    Sep 1, 2016 at 14:23
  • 1
    @venki421: 1 is a true expression, which cause awk to perform default print $0.
    – cuonglm
    Sep 1, 2016 at 15:52
0

Modify your script on this way:

awk '{if (NR>=2&&NR<=5) $7=60; print}' input.dat > tmp && mv tmp input.dat

The problem you observe in your variant is because w/o explicit print clause awk will print the input line

3
  • but this replaces all my file to replaced lines. I only want to change the line 2~5.
    – user42298
    May 16, 2015 at 12:27
  • So I just added two more commands, sed -i "2,5d" input.dat and sed -i "1 r tmp" input.dat . Is there good way to do this?
    – user42298
    May 16, 2015 at 12:34
  • Yes, see my edited answer May 16, 2015 at 12:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .