sed substitution for specific record

Hi, I have a file with two different people, each with there own figure next to it. How would I use a sed command to try and change the correct corresponding value? or is another command more appropriate? I have tried

sed -n '/dan/p' money | sed -i 's/1000/1500/g' money 

the file contents are as follows

dan    1000
john   1200

this does not seem to work in such a way that if both numeric values were identical that only the relevant one would be changed :wall:

Can you pls post some input that support your requirement and desired output.

1 Like

What im tring to do is add a value onto each persons value and then update the original file which holds this data. Im aware that if i dont specify the correct record then if two values are the same it could lead to both being updated. I hope that helps

a=`sed -n '/dan/p' money | cut -f2`
b=100
c=`expr $a + $b`

echo "your new balance is $c"
sed -n '/dan/p' money | sed -i 's/1000/1500/g' money

First: if your input file and output file are the same than sed will destroy the file. Use a different file for output.

Second: have a look at the man page for sed, about line ranges. You also might want to read this thread for an explanation and an example for how this works.

I hope this helps.

bakunin

1 Like

I think what you want is:

sed '/dan/ s/1000/1500/'

This will do the substitution only on the lines that match 'dan'.
Note that if a line contains "Maydan" or something, it will change this also, so it's safer to use anchors:

sed '/^dan/ s/1000/1500/'

which will match only lines starting with 'dan'.

1 Like

or you can do like this

$cat infile
dan 1000
john 1200
jim 100
marc 5000
hazel 25
mitch 5000
incr=5000
awk -v bal="$incr" '$1=="dan" && $2=$2+bal;$1!="dan"' infile