Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Changing the content of a file using a shell script 1

Status
Not open for further replies.

bazil2

Technical User
Feb 15, 2010
148
0
0
DE
I have some xml files and would like to change the content of them by means of a shell script.

Here is an example; the format is always the same:

<?xml version="1.0" encoding="ISO-8859-1"?>
<job>
<test>\\server\share\path\to\file.content</test>
</job>

My goal is to create a shell script that will change '.content' to '.jdf'

Is this possible to do?

Many thanks
 
Hi

Everywhere ?
Code:
sed -i 's/\.content/.jdf/g' *.xml
Or only inside test tags ?
Code:
sed -ri 's/(<test>[^<>]*)\.content([^<>]*<\/test>)/\1.jdf\2/g' *.xml
Assuming you are using GNU [tt]sed[/tt].


Feherke.
 
(Elementary user)

Thank you very much; I'm using RHEL and it also has sed

Before trying this, can I confirm that it only affects the files in my current path?

For example:

# cd /path/to/my/files
# ls
# test.txt test2.xsd test3.csv

If I then execute the code, will it only search and replace the text in the files listed above?

Best regards
 
Hi

Yes, *.xml will expand only to matching files in the current directory.

To see the command to which will be expanded, you can put an [tt]echo[/tt] in front of it :
Code:
[highlight]echo[/highlight] sed -i 's/\.content/.jdf/g' *.xml


Feherke.
 
Thank you once again - it works beautifully!

One last question, once the sed command has completed its function can the files be moved to an alternative location?

Would my approach be OK:


sed -i 's/\.content/.jdf/g' *.xml -exec /usr/bin/mv {} /move/updated/files/here/ \;

Best regards
 
Hi

Maybe like this :
Code:
sed -i 's/\.content/.jdf/g' *.xml && mv *.xml /move/updated/files/here/
But better explain the conditions of moving. The original file or the modified file ? Only on success or always ? Only the modified files or all XMLs ?

( Note that [tt]sed[/tt] with an [tt]-i[/tt] option alone overwrites the original files, but if you pass a value after [tt]-i[/tt] it will create backup files using that value as extension. )


Feherke.
 
Success!

Thank you very much for all your help
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top