Reputation: 2024
I do some research on how to replace text between delimiters, but because of lack knowledge in awk and sed I couldn't adjust command for my problem. The most similar question I found here, but after adjusting command to awk '/^(name=|&)/{f=f?0:1}f&&/*/{$0="//" $0}1' file
it didn't work. Also, I would like do replace using variable instead of doing replace in file. And if I didn't ask to much, very short explanation would be great :)
I have next url in variable $url
and variable $new=unnamed384
:
http://www.example.com/?name=unnamed293&file=4
I need to replace text between "name=" and "&" with variable $new
.
E.g. This is variable $url
before:
http://www.example.com/?name=unnamed293&file=4
This is variable $url
after:
http://www.example.com/?name=unnamed384&file=4
Upvotes: 2
Views: 3663
Reputation: 85865
How about:
$ new="unnamed384"
$ url="http://www.example.com/?name=unnamed293&file=4"
$ sed "s/name=[^&]*/name=$new/" <<< $url
http://www.example.com/?name=unnamed384&file=4
Upvotes: 3
Reputation: 3880
$new='unnamed384';
$echo 'http://www.example.com/?name=unnamed293&file=4' | awk -F'[=&]' '{ print $1"=""'"$new"'""&"$3"="$4 }'
http://www.example.com/?name=unnamed384&file=4
Upvotes: 0
Reputation: 67291
s/(.*\?name=)[^\&]*(&.*)/$1$n$2/g
The above will do. tested below(used with perl)
> echo "http://www.example.com/?name=unnamed293&file=4"
http://www.example.com/?name=unnamed293&file=4
> echo "http://www.example.com/?name=unnamed293&file=4" | perl -lne '$n="unamed394";$_=~s/(.*\?name=)[^\&]*(&.*)/$1$n$2/g;print'
http://www.example.com/?name=unamed394&file=4
>
Upvotes: 1