Replace parameters in a text file

Matej

I have alot of text files with the folling structure: FileName_Location.txt. Within the textfile there are three values, which i have to replace.

<filename="" location="" extension="">

So it would be <filename="FileName" location="Location" extension="txt">

I get all those values by the filename. But it could also be possible that the values/parameters in the textfile are wrong, so I have to overwrite them.

My problem is how I can exact locate the right positions to add or replace the values.

Tim Biegeleisen

Here is Java code making heavy use of regular expressions which works on a single line from your original question. It extracts out several groups and then rebuilds the line, inserting the values you want along the way.

String pattern = "^(<filename=)(\".*\")\\s(location=)(\".*\")\\s(extension=)(\".*\">)$";
String input = "<filename=\"\" location=\"\" extension=\"\">";
// you can uncomment this next line to test the case when values be
// already present in the input line
//String input = "<filename=\"stuff\" location=\"stuff\" extension=\"stuff\">";
System.out.println("Input string:");
System.out.println(input);

// you can replace these next 3 variables with whatever values you want
// e.g. you could put this code into a loop
String fileName = "FileName";           // a new filename
String location = "Location";           // a new location
String extension = "txt";               // a new extension
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
if (m.find()) {
    StringBuilder res = new StringBuilder();
    res.append(m.group(1)).append("\"").append(fileName).append("\" ");
    res.append(m.group(3)).append("\"").append(location).append("\" ");
    res.append(m.group(5)).append("\"").append(extension).append("\">");
    System.out.println("Output string:");
    System.out.println(res);
} else {
    System.out.println("NO MATCH");
}

This code has been tested on IntelliJ version 11 (yes I'm too lazy to upgrade) and it works fine.

Output:

Input string:
<filename="" location="" extension="">
Output string:
<filename="FileName" location="Location" extension="txt">

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related