vincent
vincent

Reputation: 55

replace parts of url with sed in a file

I have a file full of urls that looks like this:

https://testing/this/string/for/now

which I need to have them all replaced using sed specifically, to:

https://testing/this/now

and save the file at the end with the updated content. So actually remove whatever content exists in the 'string' and 'for'(no matter their length might be), but keep the latter 'now' part of the url.

Thanks in advance.

Vincent

Upvotes: 2

Views: 1874

Answers (2)

twalberg
twalberg

Reputation: 62379

Here's a simple solution using cut:

# echo https://testing/this/string/for/now | cut -d/ -f1-4,7
https://testing/this/now

To process a file, just run cut -d/ -f1-4,7 < input.txt > output.txt.

Upvotes: 1

anubhava
anubhava

Reputation: 785128

You can use this sed command to remove 2 paths after https://testing/this/:

sed -i.bak 's|\(https://testing/this/\)[^/]*/[^/]*/|\1|'' file

Explanation:

\(https://testing/this/\)  # match and group https://testing/this/
[^/]*/                     # match 0 or more of any character that is not /
[^/]*/                     # match 0 or more of any character that is not /

In replacement we're using \1 which is back-reference to first capturing group.

Example:

s='https://testing/this/string/for/now'
sed 's|\(https://testing/this/\)[^/]*/[^/]*/|\1|' <<< "$s"
https://testing/this/now

Upvotes: 2

Related Questions