Replace string in a file

Four Stars

Replace string in a file

Hi All,
I have a problem with Talend, I cannot find any answer to my problem.
I have a directory with various xml files inside, each xml is different (not the same structure)
I have to replace one of the first line of each xml file, in the first tag there is a key name (always the same name) and I have to change the value.
example : <my tag myKey="blablabla" >
and replace it like : <my tag myKey="anotherblablabla" >
So I start my job like this :
tFileList->tFileInputFullRow->tJavaRow-> ????
So tFileList is listing my files, no problem,
I user tFileInputFullRow because the tFileInputXml want my to describe my xml schema, or each file can a a different schema.
So in tJavaRow, I read the current row, if I find myKey, I can replace the content, that's ok.
But now, how I can replace the line in the file ? How I can tell, replace current line in the file ?
I don't want to create a new file with each iteration (by rewriting line by line) because it will spend a lot of time for just one change.
Hope that someone can help me Smiley Happy
Thanks !
Four Stars

Re: Replace string in a file

You should be able to do this using a shell script (on Linux/UNIX) or batch program (Windows). Assuming it's Linux, you could use the sed utility to find and replace instances of they key in the files, without caring about their structures.

Using sed, the following code replaces all occurences of Mary Sanders to Mary Jones in the file customer.txt:

cat customer.txt | \
sed -e 's/Mary Sanders/Mary Jones/' > customer.txt

So in your case, it would be:

"/bin/sh " +
" cat " + ((String)globalMap.get("tFileList_1_CURRENT_FILEPATH")) + " | \" +
" sed -e 's/blablabla/anotherblablabla/' > " + ((String)globalMap.get("tFileList_1_CURRENT_FILEPATH"))
I've not tested this end to end - but should work based on similar stuff I've done...
Seventeen Stars

Re: Replace string in a file

After your tJavaRow you have to write line by line into a new file, backup to old one and rename the new into the old file name.


Talend named a Leader.

Get your copy


Kickstart your first data integration and ETL projects.

Download now

What’s New for Talend Summer ’19

Watch the recorded webinar!

Watch Now

Best Practices for Using Context Variables with Talend – Part 4

Pick up some tips and tricks with Context Variables


How Media Organizations Achieved Success with Data Integration

Learn how media organizations have achieved success with Data Integration


Why Companies Move to the Cloud: 7 Success Stories

Learn how and why companies are moving to the Cloud

Read Now