Home > Software design >  How to use "sed" or "awk" to replace url parameters query string
How to use "sed" or "awk" to replace url parameters query string

Time:11-28

I was trying to replace the query string with my custom value of any url. But it is not parsing it correctly.

echo "http://sub.domain.com/file.jsp;jsessionid=2e62dbe69850d25bc7c6424ba59db?one=15&two=16" | sed -e "s!=[^&]*!=SOMETHING!g"

http://sub.domain.com/file.jsp;jsessionid=SOMETHING&two=SOMETHING

but I want result like this

http://sub.domain.com/file.jsp;jsessionid=SOMETHING?one=SOMETHING&two=SOMETHING

Is there any way to do it using sed or awk

CodePudding user response:

Try this:

#!/bin/bash

url="http://sub.domain.com/file.jsp;jsessionid=2e62dbe69850d25bc7c6424ba59db?one=15&two=16"

echo "ORIGINAL: $url"
echo "NEW:      $url" | sed -e 's#\(.*jsessionid=\).*\(?one=\).*\(&two=\).*$#\1SOMETHING1\2SOMETHING2\3SOMETHING3#'

Result:

ORIGINAL: http://sub.domain.com/file.jsp;jsessionid=2e62dbe69850d25bc7c6424ba59db?one=15&two=16
NEW:      http://sub.domain.com/file.jsp;jsessionid=SOMETHING1?one=SOMETHING2&two=SOMETHING3

The method I used is to keep everything you want, and replacing what you do not want with the values you desire. So replace SOMETHING1-2-3 with whatever you want to use.

It does make it longer but simpler to understand, IMHO.

CodePudding user response:

Using sed

$ sed 's/=[^?\|&]*/=SOMETHING/g' input_file
http://sub.domain.com/file.jsp;jsessionid=SOMETHING?one=SOMETHING&two=SOMETHING
  • Related