user1718482
user1718482

Reputation:

Perl replace regular expression

In file.txt I have a line like this:

^/string string_to_be_replaced

that must become:

^/string replaced_string

So I created a perl script:

perl -pi -e "s[\^/string$(.*)$] [\^/string$(.*) replaced_string]" /file.txt

But the problem is that perl doesn't find the line starting with ^/string

Upvotes: 0

Views: 142

Answers (2)

Dave Sherohman
Dave Sherohman

Reputation: 46187

The first portion of your regex, [\^/string$(.)$], looks for a line containing "^/string", followed by an end-of-line, followed by a single character (which is captured), and finally another end-of-line. Since the file is processed line-by-line (looking at only one line at a time), a pattern containing two end-of-lines can never match.

You probably want:

s[\^/string string_to_be_replaced][^/string replaced_string]

assuming that you have only a single string_to_be_replaced and only want to replace it when it's preceded by string. If not, then more details would be useful.

Upvotes: 1

mpapec
mpapec

Reputation: 50637

perl -pi -e "s[\^/string .+$][^/string replaced_string]" /file.txt

or

perl -pi -e "s[\^/string \K.+$][replaced_string]" /file.txt

Upvotes: 1

Related Questions