0

I'm new to Perl and trying to replace a line in a text file using a wildcard. Example file:

This is a text file.

My working (non-wildcard) example:

file=/home/test.user/test.txt
perl -pi -e 's/This is a text file./'"This is a modified text file."'/g' $file

Now trying to edit with a wildcard:

perl -pi -e 's/This*/'"This is a modified text file."'/g' $file

This is incorrect, and outputs:

This is a modified text file. is a text file.

How can I use a wildcard search with /This*/?

1
  • 3
    I recommend reading the documentation for a language rather than guessing at its syntax, especially before asking the world for help. Perl uses regular expressions after the fashion of awk and sed. There is no reason to assume that a shell glob syntax is appropriate here. Commented Aug 21, 2018 at 14:58

1 Answer 1

1

Perl's s/// uses a regular expression pattern to match the target, not a shell glob string.

Instead of *, try .* like this:

perl -pi -e 's/This.*/'"This is a modified text file."'/g' $file

.* matches zero or occurrences of any character except linefeed LF or "\n".

Be careful, because it will match the substring anywhere in the string. So this string:

If This is a text file

will become this string:

If This is a modified text file

Therefore if you want to match beginning of line, then use an anchor ^ which insists that the rest of the pattern must match at the start of the string

perl -pi -e 's/^This.*/'"This is a modified text file."'/g' $file
Sign up to request clarification or add additional context in comments.

Comments

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.