jacob
jacob

Reputation: 2896

Complex string replacement

I have an html file which contains a line like this:

base_url = '',

Sometimes there may be nothing between the single quotes; sometimes there might be a url there. How do I write single line perl command which fills in the string with a base url?

I tried this, but it doesn't work:

perl -pe 's/(base_url = \')(.+)/https:\/\/www\.example\.com(\',)/eg' -i index.htm

Thanks

Upvotes: 0

Views: 148

Answers (2)

Gene
Gene

Reputation: 46960

You asked for a one-liner but didn't say which shell you're using. This matters a lot. I'll assume bash. This is one way:

perl -p -e 's#(base_url *= *)'"'"'.*'"'"'#$1'"'"'https://www.example.com/'"'"'#'

As you can see, the hard part is escaping single quotes within single quotes. There may be a simpler way to do it, but I don't know what that is.

Some folks don't seem to like the single quote escape within single quotes convention. I like it because you don't have to worry about any further shell escapes. Here's an answer with double quotes:

perl -p -e "s#(base_url *= *)'.*'#\$1'https://www.example.com/'#"

Upvotes: -1

C. K. Young
C. K. Young

Reputation: 223023

Try this:

s|base_url = '.*?',|base_url = 'https://www.example.com/',|g;

Upvotes: 3

Related Questions