简体   繁体   中英

replace part of first line in a multi line string

I have a file with multiple lines. I read the file using read_file and put the entire string into a scalar string.

My Sample file format,

From : test@gmail.com
To : test1@gmail.com
Subject : Test Mail

and so my string will be like this,

$mystring = "From : test@gmail.com\nTo : test1@gmail.com\nSubject : Test Mail"

These are template files already generated with random address in From and To field. I want to change the From field alone with the custom one as below,

$mystring = "From : user1@yahoo.com\nTo : test1@gmail.com\nSubject : Test Mail"

All I have to do is search and replace the From field in a multi line string using perl. I am new to perl and don't have great exposure to it.

If you want to use a file as template to create another file, you can use shell redirection along with the -p switch for Perl in a one-liner:

perl -pe 's/^From\s*:\s*\K.*/user1\@yahoo.com/' input > output 

This will apply the substitution s/.../.../ to all lines in the file and print the output to file. The regex explanation:

  • ^ match beginning of string
  • \\s* match whitespace 0 or more times
  • \\K keep what is left of this symbol
  • .* match any character except newline 0 or more times

The .* will consume the rest of the line, and the \\K escape will preserve the From: part, inserting the new email afterwards. Note that you need to escape the @ character to prevent variable interpolation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM