0

Is it possible to create a diff patchfile that will edit lines themselves, rather than replacing an entire line?

For example, I have the following line:

 <foo:ListeningPortBar>3423</foo:ListeningPortBar>

and I want to change this to:

 <cat:LoremIpsum>3423</cat:LoremIpsum>

That is, I want to change the text around the actual port number, but preserve the port number - I need to apply this patch across a number of files, all with different port numbers - I simply want to change the tags, keeping whatever port number is in there currently.

How can you achieve this please?

Thanks, Victor

1 Answer 1

0

It doesn't really matter if a patch replaces the entire line or just characters in the line (the end result is the same, no...?), but I don't think this is a "patch" question. See below for a simpler solution using "sed".

For example, assume:

$ cat f1.txt
<xml>
<foo:ListeningPortBar>3423</foo:ListeningPortBar>
</xml>

$cat f2.txt
<xml>
<cat:LoremIpsum>3423</cat:LoremIpsum>
</xml>

Then, literally the patch would be:

$ diff -u f1.txt f2.txt
--- f1.txt  2012-07-08 03:14:39.328328048 -0700
+++ f2.txt  2012-07-08 03:14:30.618177130 -0700
@@ -1,3 +1,3 @@
 <xml>
-<foo:ListeningPortBar>3423</foo:ListeningPortBar>
+<cat:LoremIpsum>3423</cat:LoremIpsum>
 </xml>

This patch file could be used as a template, modified with correct values for all your files that need to be updated, and applied to all the files individually. That sounds like more work than necessary.

On the other hand, just use "sed":

$ sed 's/<foo:ListeningPortBar>\([0-9]*\)<\/foo:ListeningPortBar>/<cat:LoremIpsum>\1<\/cat:LoremIpsum>/' f1.txt  
<xml>
<cat:LoremIpsum>3423</cat:LoremIpsum>
</xml>

Since you have XML, using xsltproc is another alternative, but again probably overkill for this simple search-and-replace task.

To use this in a script, you'd do something like (replacing "etc/etc" with the sed above):

for f in $(find dir -name "*.xml" -exec egrep 'foo:ListeningPortBar' {} \; -print)
do
  sed -i.bak 's/etc/etc/g' $f
done

...and then verify that the ".bak" files are actually different than the modified files.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.