0

I have a file containing a line like

https://abcdefgh.com/123/pqrst/456/xyz.html

So I want to search for this line in that file and replace the end part i.e. xyz.html with mno.html

Will take the mno.html as input in the shell script.

How to do that ?

3 Answers 3

2
$ awk 'BEGIN{FS=OFS="/"} index($0,"https://abcdefgh.com/123/pqrst/456/xyz.html"){$NF="mno.html"} 1' file
https://abcdefgh.com/123/pqrst/456/mno.html

or if both values are already stored in shell variables:

$ old="https://abcdefgh.com/123/pqrst/456/xyz.html"
$ new="mno.html"
$ awk -v old="$old" -v new="$new" 'BEGIN{FS=OFS="/"} index($0,old){$NF=new} 1' file
https://abcdefgh.com/123/pqrst/456/mno.html
Sign up to request clarification or add additional context in comments.

Comments

0

You can use this sed,

sed '/https:\/\/abcdefgh.com\/123\/pqrst\/456\/xyz.html/s#\(.*\/\)\(.*\)#\1mno.html#g' yourfile

1 Comment

You should escape the . in .com and .html. It's also worth telling the OP they'd need to escape every other possible RE metacharacter, etc. that can occur in filenames too (e.g. *).
0

using awk if the line is exactly as the example, I mean if there is no other characters before or after it

awk '{print gensub(/^(https:\/\/abcdefgh.com\/123\/pqrst\/456\/)xyz.html$/,"\\1mno.html","g")}' input.txt

Otherwise:

awk '{print gensub(/(https:\/\/abcdefgh.com\/123\/pqrst\/456\/)xyz.html/,"\\1mno.html","g")}' input.txt

1 Comment

You should mention this is GNU awk specific. You should escape the . in .com and .html. It's also worth telling the OP they'd need to escape every other possible RE metacharacter, etc. that can occur in filenames too (e.g. *). To be honest, though, I'd just use sed if I was going with an RE replacement approach and was OK with having to escape a bunch of characters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.