Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

7
  • Thanks, I tried: perl -i -0 -pe '$b = `cat before.txt`; $a = `cat after.txt`; s/\Q$b\E/$a/s\' text.txt, but it is still not working correctly. I got it working in one instance by making sure the string in before exactly matches the whole lines in which the strings was to be replaced. But it does not work for instance to replace a string that is not found at the start of the line. Example: text.txt file containing: Here is some text. before.txt contains: text after.txt contains: whatever No chance is made. (New lines are not shown in comments. Moved it to question.) Commented Dec 7, 2019 at 15:25
  • @Kvothe, in your example, the main file contains text.\n, while before.txt contains text\n. The other has a dot in before the newline, the other doesn't, so they don't match. You could use chomp $b after reading into $b to remove a possible trailing newline from it if you don't want to match it. (I only tested with full lines, so I didn't think of that case.) Commented Dec 7, 2019 at 17:38
  • Thanks! How do I use chomp. I tried adding $b = chomp($b), plus variations with backticks and different places of chomp, i.e. chomp($b = `cat before. txt`), but did not manage to get it working. Commented Dec 9, 2019 at 15:56
  • @Kvothe, I've just used chomp $b, it modifies the variable directly. chomp($b = cat before.txt) seems to work too, it's also mentioned in the docs for chomp. Commented Dec 9, 2019 at 16:31
  • Thanks, are you saying that your last command works for you for the simple test case I proposed? For me it does not. It still does not seem to find a match. (The file is overwritten but the text remains the same, same as would happen when the pattern does not occur). Commented Dec 9, 2019 at 16:49