Alam
Alam

Reputation: 325

Changing values at multiple rows and columns using awk

I have a list of values. I want to shift the values at specific rows and 2nd column by 0.2. That is-

1 2 3
4 5 6  
7 8 9

into

1 2.2 3
4 5 6
7 8.2 9

....

for row in 1, 3,6,24,41,47,42,48,29,35,30,36,17,23,18,24
do
slight_up_COORD=`echo "$slight_up_COORD"|awk 'FNR =="${row}" {a=$2} FNR=="${row}" {$2=a+0.2} {print}'`
done

Upvotes: 0

Views: 240

Answers (3)

karakfa
karakfa

Reputation: 67567

another awk approach

$ seq 9 | paste -d' '  - - - | 
  awk -v rows="1,3,6,24" -v c=, 'c rows c ~ c NR c {$2+=.2}1'

1 2.2 3
4 5 6
7 8.2 9

if you data is in a file

$ awk -v rows="1,3,6,24" -v c=, 'c rows c ~ c NR c {$2+=.2}1' file

Upvotes: 1

James Brown
James Brown

Reputation: 37464

As you already have the list of records numbers in comma-delimited list to process, we're going to be practical and use it by reading it in from the STDIN:

$ echo 1, 3,6,24,41,47,42,48,29,35,30,36,17,23,18,24 |
awk '
NR==FNR {
    for(i=1;i<=NF;i++)   # all comma-separated fields
        p[$i+0]          # hash and fix that space in the list with +0
        next             # on to the file
}

(FNR in p) {             # if the record number is in the p hash to be processed
        $2+=.2           # add 0.2 to $2 (this could be $2 ".2" but for change)
        # $2=$2 ".2"     # for non-numeric data
}1' FS=, - FS=\  file    # stdin first, comma delim, then file, space delim

Output:

1 2.2 3
4 5 6  
7 8.2 9

Upvotes: 2

RavinderSingh13
RavinderSingh13

Reputation: 133780

Could you please try following, where in split you need to define all the line numbers for which you want to add .2 in lines. In here I have done for 1,3,6 you could mention more lines here.

awk '
BEGIN{
  num=split("1,3,6",array,",")
  for(i=1;i<=num;i++){
    array1[array[i]]
  }
}
FNR in array1{
  $2+=.2
}
1
' Input_file

Explanation: Adding detailed explanation for above code here.

awk '                               ##Starting awk program from here.
BEGIN{                              ##Starting BEGIN section of this awk program from here.
  num=split("1,3,6",array,",")      ##Splitting 1,3,6 values into array with delimiter comma and getting their total length(of passed line numbers) in variable named num here.
  for(i=1;i<=num;i++){              ##Starting a for Loop starting from i=1 to value of num
    array1[array[i]]                ##Creating array named array1 whose index is array[i] value.
  }
}
FNR in array1{                      ##Checking condition if current line number is present in array1 then do following.
  $2+=.2                            ##Adding .2 to current Line 2nd field here.
}
1                                   ##1 will print edited/non-edited lines here.
' Input_file                        ##Mentioning Input_file name here.

Upvotes: 2

Related Questions