Boschko
Boschko

Reputation: 374

Perl: How to substitute the content after pattern CLOSED

So I cant use $' variable

But i need to find the pattern that in a file that starts with the string “by: ” followed by any characters , then replace whatever characters comes after “by: ” with an existing string $foo

im using $^I and a while loop since i need to update multiple fields in a file.

I was thinking something along the lines of [s///]

s/(by\:[a-z]+)/$foo/i

I need help. Yes this is an assignment question but im 5 hours and ive lost many brain cells in the process

Upvotes: 0

Views: 640

Answers (1)

showaltb
showaltb

Reputation: 998

Some problems with your substitution:

  1. You say you want to match by: (space after colon), but your regex will never match the space.
  2. The pattern [a-z]+ means to match one or more occurrences of letters a to z. But you said you want to match "any characters". That might be zero characters, and it might contain non-letters.
  3. You've replaced the match with $foo, but have lost by:. The entire matched string is replaced with the replacement.
  4. No need to escape : in your pattern.
  5. You're capturing the entire match in parentheses, but not using that anywhere.

I'm assuming you're processing the file line-by line. You want "starts with the string by: followed by any characters". This is the regex:

/^by: .*/

^ matches beginning of line. Then by: matches exactly those characters. . matches any character except for a newline, and * means zero-or more of the preceding item. So .* matches all the rest of the characters on the line.

"replace whatever characters that come after by: with an existing string $foo. I assume you mean the contents of the variable $foo and not the literal characters $foo. This is:

s/^by: .*/by: $foo/;

Since we matched by:, I repeated it in the replacement string because you want to preserve it. $foo will be interpolated in the replacement string.

Another way to write this would be:

s/^(by: ).*/$1$foo/

Here we've captured the text by: in the first set of parentheses. That text will be available in the $1 variable, so we can interpolate that into the replacement string.

Upvotes: 1

Related Questions