How can I replace the values of parameters step by step.
What I mean is,
For Example-
Url is
https://example.com/?p=first&q=second&r=third
First I want to add '123' on p param
https://example.com/?p=123&q=second&r=third
Then again with same URL but different parameter, such as q param
https://example.com/?p=first&q=123&r=third
Again with same URL but different parameter,
https://example.com/?p=first&q=second&r=123
What I tried:
while read line; do
first_part=`echo $line | cut -d'=' -f1` second_part=`echo $line | cut -d'=' -f2`
echo "${first_part}=123${second_part}"
echo "${first_part}${second_part}=123"
done < urls.txt
CodePudding user response:
The problem described is a good application for AWK's capabilities. The demo script includes samples for both URLs and a mapping functions file for global transformation of URLs.
This approach allows for parameters to "free float", not dependent on matching at a specific sequential position in the URL string.
This approach also allows for parameters to be strings of any length.
#!/bin/bash
#QUESTION: https://stackoverflow.com/questions/75124190/how-to-replace-the-values-of-a-param
cat >URL.list <<"EnDoFiNpUt"
https://example.com/?p=first&q=second&r=third
https://example.com/?r=zinger
https://example.com/?r=bonkers&q=junk&p=wacko
https://example.com/?p=flyer
EnDoFiNpUt
cat >mapfile.txt <<"EnDoFiNpUt"
q=SECOND
r=THIRD
p=FIRST
EnDoFiNpUt
awk -v datFile="mapfile.txt" 'BEGIN{
## Initial loading of the mapping file into array for comparison
split( "", transforms ) ;
indexT=0 ;
while( getline < datFile ){
indexT ;
transforms[indexT]=$0 ;
} ;
}
{
### Split off beginning of URL from parameters
qPos=index( $0, "?" ) ;
beg=substr( $0, 1, qPos ) ;
### Load URL elements into array for comparison
rem=substr( $0, qPos 1 ) ;
n=split( rem, parts, "&" ) ;
### Match and Map transforms elements with URL parts
for( k=1 ; k<= indexT ; k ){
dPos=index( transforms[k], "=" ) ;
fieldPref=substr( transforms[k], 1, dPos ) ;
for( i=1 ; i<=n ; i ){
if( parts[i] ~ fieldPref ){
parts[i]=transforms[k] ;
} ;
} ;
} ;
### Print transformed URL
printf("%s%s", beg, parts[1] ) ;
for( i=2 ; i<=n ; i ){
printf("&%s", parts[i] ) ;
} ;
print "" ;
}' URL.list
The output looks like this:
https://example.com/?p=FIRST&q=SECOND&r=THIRD
https://example.com/?r=THIRD
https://example.com/?r=THIRD&q=SECOND&p=FIRST
https://example.com/?p=FIRST
CodePudding user response:
HTML params are, by spec, orderless, so you can simply place p=
's new value at the tail instead of original position :
echo 'https://example.com/?p=first&q=second&r=third' |
mawk NF=NF FS='p=[^&]*[&]?' OFS= ORS='&p=123\n'
1 https://example.com/?q=second&r=third&p=123
same for q=
.
if you're modifying r=
instead, then set both FS
and OFS
to "="
, and do it it like a vanilla value update for $NF