I have to replace the first instance of a number in a column with some other number.
This is what I want to do
input:
54 679 75 98 21
24 543 86 98 43
42 543 54 98 55
93 255 25 98 25
43 523 43 98 31
98 775 24 76 78
77 564 65 76 45
output:
54 679 75 98 21
24 543 86 98 43
42 543 54 98 55
93 255 25 98 25
43 523 43 98 31
98 775 24 91 78
77 564 65 76 45
So that first occurrence of 76 in fourth column is replaced by 91.
This was what I was trying to do using awk:
awk '{count=0;if ($4 == 76 && count < 1){ gsub("91","76")} count++; print}' input > output
But this is not helping, can anybody suggest something?
A little tweak to stack0114106's answer, to make it even more concise:
awk '!t && $4==76 { $4=91; t=1;} 1 ' file
Variables in awk that didn't assigned will have 0 or empty string value, negate it will give true.
And I put !t before the other compare equation is for efficiency, because && is a shortcut operator, it will stop the second part from executing when the first part evaluates to false.
Last 1 is to produce a true there, a condition without block will have {print $0} block implied.
Could you please try following(using this approach we are mentioning all the values in variables and nothing hard-coded, for any further values changes simply change the variable values and program should still work).
awk -v column="4" -v count="1" -v value="76" -v new_value="91" '($column == value){if(++num==count){$column=new_value}} 1' Input_file
Or adding a non-one liner form of solution.
awk -v column="4" -v count="1" -v value="76" -v new_value="91" '
($column == value){
if(++num==count){
$column=new_value
}
}
1
' Input_file
Output will be as follows.
54 679 75 98 21
24 543 86 98 43
42 543 54 98 55
93 255 25 98 25
43 523 43 98 31
98 775 24 91 78
77 564 65 76 45
EDIT: correcting OP' attempt and adding corrections details too.
Code should be changed to:
awk '{if ($4 == 76){if(++count == 1){sub("^" 76 "$","91",$4)}};print}' Input_file
Explanation of above FIX of OP's code:
count=0 is a bug here since every time a new line is getting read it will make variable count's value to 0 and program will NEVER know how many times 76 came in 4th field so I removed it.count<0 which actually should be ++count==1 and should be inside of BLOCK of condition $4==76 why because eve condition is NOT TRUE($4==76) variable count's value is keep increasing so let us increase then when condition $4==76 is TRUE and then it will keep its count correctly.gsub even above is FIXED still code will NOT work why because (g)sub pattern is sub(current_value,replaced_value) so you are substitution 91 with 76 which is totally opposite of your ask, and after this FIX your code should work well :)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With