Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a specific field with sed

Tags:

shell

unix

sed

awk

I'm trying to update a specific field on a specific line with the sed command in Bourne Shell.

Lets say I have a file TopScorer.txt

Player:Games:Goals:Assists
Salah:9:9:3
Kane:10:8:4

And I need to update the 3rd Column (Goals) of a player, I tried this command and it works unless Games and Goals have the same value then it updates the first one

player="Salah"
NewGoals="10"
OldGoals=$(awk -F':' '$1=="'$player'"' TopScorer.txt | cut -d':' -f3)
sed -i '/^'$player'/ s/'$OldGoals'/'$NewGoals'/' TopScorer.txt

Output> Salah:10:9:3 instead of Salah:9:10:3

Is there any solution? Should I use delimiters and $3==... to specify that field? I also tried the option /2 for second occurrence but it's not very convenient in my case.

like image 913
Common Avatar asked Dec 31 '25 01:12

Common


1 Answers

You can just do this with awk alone and not with sed. Also note that awk has an internal syntax to import variables from the shell. So your code just becomes

awk -F: -v pl="$player" -v goals="$NewGoals" 
    'BEGIN { OFS = FS } $1 == pl { $3= goals }1' TopScorer.txt

The -F: sets the input de-limiter as : and the part involving -v imports your shell variables to the context of awk. The BEGIN { OFS = FS } sets the output field separator to the same as input. Then we do the match using the imported variables and update $3 to the required value.

To make the modifications in-place, use a temporary file

awk -F: -v pl="$player" -v goals="$NewGoals" 
   'BEGIN { OFS = FS } $1 == pl { $3= goals }1' TopScorer.txt > tmpfile && mv tmpfile TopScorer.txt
like image 53
Inian Avatar answered Jan 01 '26 17:01

Inian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!