One Star

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 !
One Star

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.