简体   繁体   中英

How to edit bash text file using sed

genius:johnny bravo:56.80:100:38

hello:jack john:89.10:290:189

i have the above 2 lines inside my text file test.txt i wish to change the last value, in this case 189 to 50, if user enters field 1 and field 2 correctly.

what i've done but isn't working

read title # genius/joker
read name  # jonny bravo or jack john
echo "enter new value"
read newValue
sed -i "s/^\($title:$name:[^:]*\):[^:]*:/\1:$newValue:/" test.txt 

from my sed, i realize that the 4th field of code is change, in this case 290 is changed to new value instead of 189. Can any of you enlighten me on where did i go wrong?

Thanks in advance

awk suites better for this case:

title="hello"
name="jack john"
n=50
awk -v f1="$title" -v f2="$name" -v n=$n -F: '$1==f1 && $2==f2{$NF=n}1' OFS=: file

OUTPUT:

genius:johnny bravo:56.80:100:38
hello:jack john:89.10:290:50

Your regex is incorrect. Try this:

sed -i "s/^\($title:$name:.*\):.*$/\1:$newValue/" test.txt 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM