C# - Replace text mid-string and keep the rest of the string, duplicate lines -
i have 2 .txt documents , search in 1 of them keys secoond file. if keys found, want replace match text follows key in second file. also, add "t" or "b" depending on number in file.
here example of first file:
1 0010 sometext/numbers text, text .2 0020 sometext/numbers text, text, text 1 0020a sometext/numbers text,text .1 2000 sometext/numbers text,text, text ..3 9123a sometext/numbers text ... ... ... ...
here example of second file:
0010 abcd efg 0020 c01 0020a c02, c3, c004, c9901, c938, c12 2000 r123, r13, d34 9123a sometext ... ...
from these 2 files, use "keys" second file (at start of every new line). in example keys be: 0010, 0020, 0020a, 2000, 9123a. after have keys want search first text document in second column see if there match. if there match (in case match) replace text in first document , create new document updated text. also, if there multiple values after keys in second file, copy lines down. below see mean.
the new document this:
1 abcd efg sometext/numbers sometext, text .2 c01 sometext/numbers text, text, text 1 c02 sometext/numbers text,text //-------------------- 1 c3 sometext/numbers text,text // copied lines 1 c004 sometext/numbers text,text // down if there 1 c9901 sometext/numbers text,text // multiple values in 1 c938 sometext/numbers text,text // document 2. 1 c12 sometext/numbers sometext,text //-------------------- .1 r123 sometext/numbers text,text, text //-------------- .1 r13 sometext/numbers text,text, text // copied .1 d34 sometext/numbers text,text, text //-------------- ..3 sometext sometext/numbers text ... ... ... ...
also, if key(s) end "a" add "t" end of string above. if key(s) not end "a" add "b" end of string above.
example of few lines:
.1 r123 sometext/numbers text,text, text b //key 2000 .1 r13 sometext/numbers text,text, text b //key 2000 .1 d34 sometext/numbers text,text, text b //key 2000 ..3 sometext sometext/numbers text t //key 9123a
question(s):
- how search 1 file keys second file?
- once located, how replace item in first text item in second text?
- after replace file, must re-concatenate string?
- after each line correct, there 'best' way add "t" or "b" @ end of each line (this depends on key having "a" or not)?
- any other recommendations go this?
here code have been trying work with.. cannot how want , code not working how expected to.:
using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.linq.expressions; using system.text; using system.windows.forms; using system.io; using system.diagnostics; using system.text.regularexpressions; using system.collections; namespace bom_formatter { public partial class bomform : form { // create openfiledialogs request paths , file names open. openfiledialog openfile = new openfiledialog(); openfiledialog openrefs = new openfiledialog(); // create savefiledialog request path , file name save. savefiledialog savefile = new savefiledialog(); string filepath = "c:\\users\\filetext.txt"; string refspath = "c:\\users\\refstext.txt"; public bomform() { initializecomponent(); } //********************************************************* //******************* open file button ******************** //********************************************************* private void openbutton_click(object sender, eventargs e) { // initialize openfiledialog specify .txt extension. openfile.defaultext = "*.txt"; openfile.filter = ".txt files|*.txt"; openfile.restoredirectory = true; try { // open contents of file originaltextrichtextbox. if (openfile.showdialog() == dialogresult.ok && openfile.filename.length > 0) originaltextrichtextbox.loadfile(openfile.filename, richtextboxstreamtype.plaintext); // throws filenotfoundexception otherwise. else throw new filenotfoundexception(); // calls format opened file. openfileformathelper(); formattedtextrichtextbox.savefile(filepath, richtextboxstreamtype.plaintext); } // catches exception if file not opened. catch (exception) { messagebox.show("there not specified file path.", "path not found error", messageboxbuttons.ok, messageboxicon.warning); } } //********************************************************* //******************** open refs button ******************* //********************************************************* private void openrefsbutton_click(object sender, eventargs e) { // initialize openfiledialog specify .txt extension. openrefs.defaultext = "*.txt"; openrefs.filter = ".txt files|*.txt"; openrefs.restoredirectory = true; try { // open contents of file originaltextrichtextbox. if (openrefs.showdialog() == dialogresult.ok && openrefs.filename.length > 0) refstextrichtextbox.loadfile(openrefs.filename, richtextboxstreamtype.plaintext); // throws filenotfoundexception otherwise. else throw new filenotfoundexception(); // calls format opened refs file. openrefsformathelper(); formattedrefstextrichtextbox.savefile(refspath, richtextboxstreamtype.plaintext); } // catches exception if file not opened. catch (exception) { messagebox.show("there not specified file path.", "path not found error", messageboxbuttons.ok, messageboxicon.warning); } } //********************************************************* //******************* save file button ******************** //********************************************************* private void savebutton_click(object sender, eventargs e) { // initialize savefiledialog specify .txt extension file. savefile.defaultext = "*.txt"; savefile.filter = ".txt files|*.txt"; savefile.restoredirectory = true; try { // save contents of formattedtextrichtextbox file. if (savefile.showdialog() == dialogresult.ok && savefile.filename.length > 0) finaltextrichtextbox.savefile(savefile.filename, richtextboxstreamtype.plaintext); // throws filenotfoundexception otherwise. else throw new filenotfoundexception(); } // catches exception if file not saved. catch (exception) { messagebox.show("there not specified file path.", "path not found error", messageboxbuttons.ok, messageboxicon.warning); } } //********************************************************* //******************* clear file button ******************* //********************************************************* private void clearbutton_click(object sender, eventargs e) { try { // resets text in of boxes. originaltextrichtextbox.resettext(); formattedtextrichtextbox.resettext(); refstextrichtextbox.resettext(); formattedrefstextrichtextbox.resettext(); finaltextrichtextbox.resettext(); } // catches exception if either text box not cleared. catch (exception) { messagebox.show("could not clear text.", "clearing text box error", messageboxbuttons.ok, messageboxicon.warning); } } //********************************************************* //******************* format file button ****************** //********************************************************* private void formatbutton_click(object sender, eventargs e) { try { //var list = new list<string>(); openfileformathelper(); openrefsformathelper(); // formatallhelper(); finalformathelper(); } // catches exception if file not opened. catch (exception) { messagebox.show("could not format text.", "text formatting error", messageboxbuttons.ok, messageboxicon.warning); } } private void finalformathelper() { try { string[] openfilefinal = file.readalllines(filepath); string[] openrefsfinal = file.readalllines(refspath); var result = new list<string>(); string theoutput; // stringbuilder finaloutput = new stringbuilder(); foreach (var filelines in openfilefinal) { //match numberstartmatch = regex.match(filelines, @"^[\d]+");//[\s+[\d\w]+]*"); var fileparts = filelines.split(' '); foreach (var reflines in openrefsfinal) { var refsparts = reflines.split(' '); theoutput = fileparts.tostring(); if (fileparts[1].equals(refsparts[0])) { theoutput = fileparts[0] + "\t" + fileparts[1].replace(fileparts[1], refsparts[1]) + "\t" + fileparts[2] + "\t" + fileparts[3] + "\t" + fileparts[4]; result.add(string.join(" ", theoutput)); } else result.add(theoutput); } // finaltextrichtextbox.appendtext(result.tostring()); // otherwise keep line how is. } foreach (var line in result) { finaltextrichtextbox.appendtext(line + "\n"); } } // catches exception if file not formatted. catch (exception) { messagebox.show("there problem formatting 'final file'.", "final file format error", messageboxbuttons.ok, messageboxicon.warning); } } //********************************************************* //******************* open file helper ******************** //********************************************************* private void openfileformathelper() { try { // resets formattedtextrichtextbox multiple files aren't loaded on top of eachother. formattedtextrichtextbox.resettext(); foreach (string line in file.readalllines(openfile.filename)) { // uses regular expressions find line has, digit(s), space(s), digit(s) + letter(s), // space(s), digit(s), space(s), character (up 25 times). match thematch = regex.match(line, @"^[\.*\d]+\s+[\d\w]+\s+[\d\-\w*]+\s+.{25}"); if (thematch.success) { // stores matched value in string output. string output = thematch.value; // replaces tabs , space 1 space delimiter output = regex.replace(output, @"\s+", " "); // sets formattedtextrichtextbox string output. formattedtextrichtextbox.appendtext(output); formattedtextrichtextbox.appendtext("\n"); } } } // catches exception if file not opened. catch (exception) { messagebox.show("there problem formatting 'open file'.", "open file format error", messageboxbuttons.ok, messageboxicon.warning); } // creates final string of formatted rich text box. //string openfilefinal = formattedtextrichtextbox.text.tostring(); } //********************************************************* //******************* open refs helper ******************** //********************************************************* private void openrefsformathelper() { try { formattedrefstextrichtextbox.resettext(); // reads lines in file format. var reader = file.opentext(openrefs.filename); // creates list lines stored in. var list = new list<string>(); // adds each line in file list. while (true) { var line = reader.readline(); if (line == null) break; list.add(line); } // handles of requirements reference text. list = fourdigitrequirement(list); list = concatrequirement(list); list = startswithbrequirement(list); list = elementisbrequirement(list); list = removetrequirement(list); // prints formatted refs richtextbox. foreach (var line in list) formattedrefstextrichtextbox.appendtext(line + "\n"); // creates final string of formatted refs rich text box. //string refsfilefinal = formattedrefstextrichtextbox.text.tostring(); } // catches exception if file not formatted. catch (exception) { messagebox.show("there problem formatting 'refs file'.", "refs file format error", messageboxbuttons.ok, messageboxicon.warning); } } //********************************************************* //****************** format helper ******************** //********************************************************* /* private void formatallhelper() { try { finaltextrichtextbox.resettext(); // reads lines in file format. var filereader = file.opentext(formattedtextrichtextbox.text); var refsreader = file.opentext(formattedrefstextrichtextbox.text); // creates list lines stored in. var list = new list<string>(); var list2 = new list<string>(); // adds each line in file list. while (true) { var line = filereader.readline(); var line2 = refsreader.readline(); if (line == null) break; if (line2 == null) break; list.add(line); list2.add(line2); } list = finaltextrequirement(list, list2); // prints formatted refs richtextbox. foreach (var line in list) finaltextrichtextbox.appendtext(line + "\n"); } // catches exception if file not formatted. catch (exception) { messagebox.show("there problem formatting 'final text' file.", "final file format error", messageboxbuttons.ok, messageboxicon.warning); } } public list<string> finaltextrequirement(list<string> list, list<string> list2) { // creates variables of text in 2 rich text boxes. var openfilefinal = file.readalllines(formattedtextrichtextbox.text); var openrefsfinal = file.readalllines(formattedrefstextrichtextbox.text); stringbuilder finaloutput = new stringbuilder(); var result = new list<string>(); try { finaltextrichtextbox.resettext(); // splits text var openfilefinallines = openfilefinal.select(f => f.split(' ')).todictionary(g => g[1], h => h); var openrefsfinallines = openrefsfinal.select(f => f.split(' ')).todictionary(g => g[0], h => h[1].split(',')); foreach (var line in openfilefinallines) { if (openrefsfinallines.containskey(line.key)) finaloutput.append(combine(line.value, openrefsfinallines[line.key])); else finaloutput.appendline(string.join("\t", line.value)); } } // catches exception if final output not created. catch (exception) { messagebox.show("there problem creating final document.", "final text formatting error", messageboxbuttons.ok, messageboxicon.warning); } finaltextrichtextbox.text = finaloutput.tostring(); return result; /* // creates new list return new format. var result = new list<string>(); var openfilefinal = file.readalllines(formattedtextrichtextbox.text); foreach (var line in openfilefinallines) { if (openrefsfinallines.containskey(line.key)) finaloutput.append(combine(line.value, openrefsfinallines[line.key])); else finaloutput.appendline(string.join("\t", line.value)); } } string combine(string[] openfilefinallines, string[] openrefsfinallines) { stringbuilder abuilder = new stringbuilder(); foreach (var thestring in openrefsfinallines) { abuilder.appendline(string.format("{0}\t{1}\t{2}\t{3}\t{4}", openfilefinallines[0], thestring, openfilefinallines[2], openfilefinallines[3], openfilefinallines[1].endswith("a") ? "t" : "b")); } return abuilder.tostring(); }*/ //************************************************************* //***************** element b requirement ****************** //************************************************************* // handles requirement of second element in list being "b". static list<string> elementisbrequirement(list<string> list) { // creates new list return new format. var result = new list<string>(); // checks each line in list. foreach (var line in list) { // splits each line 'parts' var parts = line.split(' '); // checks if second 'part' array "b" if (parts[1].equals("b")) { // if "b", replace "a" , add new list "result" parts[0] += "a"; parts[1] = string.empty; result.add(string.join(" ", parts)); } // otherwise keep line how is. else result.add(line); } // returns new list can formatted further. return result; } //************************************************************* //***************** starts b requirement ***************** //************************************************************* // handles requirement of element starting "b". static list<string> startswithbrequirement(list<string> list) { // creates new list return new format. var result = new list<string>(); var = 0; // checks if line begins "b" foreach (var line in list) { // splits each line 'parts' var parts = line.split(' '); // checks if first 'part' array "b" if (parts[0].equals("b")) { // if "b", copy previous line down , add "a" "b" @ // , add new list "result" parts[0] = string.empty; result.add(list[i - 1].split(' ')[0] + "a" + string.join(" ", parts)); } // otherwise keep line how is. else result.add(line); i++; } // returns new list can formatted further. return result; } //************************************************************* //****************** concat list requirement ****************** //************************************************************* // handles requirement of concatting list. static list<string> concatrequirement(list<string> list) { // creates new list return new format. var result = new list<string>(); // checks each line in list. foreach (var line in list) { // splits each line 'parts' var parts = line.split(' '); int test; // concats if (int.tryparse(parts[0], out test) || parts[0].equals("b")) result.add(line); // otherwise result - 1 else result[result.count - 1] += line; } // returns new list can formatted further. return result; } //************************************************************* //***************** remove t requirement ****************** //************************************************************* // handles requirement of removing "t". static list<string> removetrequirement(list<string> list) { // creates new list return new format. var result = new list<string>(); // checks each line in list. foreach (var line in list) { // splits each line 'parts' var parts = line.split(' '); // checks if second 'part' array "t", if is, remove "t" if (parts[1].equals("t")) parts[1] = string.empty; // add new string result. result.add(string.join(" ", parts).replace(" ", " ")); } // returns new list can formatted further. return result; } //************************************************************* //****************** 4 digits requirement ****************** //************************************************************* // handles requirement of digits being length. static list<string> fourdigitrequirement(list<string> list) { // creates new list return new format. var result = new list<string>(); // checks each line in list. foreach (var line in list) { // splits each line 'parts' var parts = line.split(' '); int test; // checks if array[0] (digits) proper length. if (int.tryparse(parts[0], out test)) { // if not length of 4 digits, add "o" front until is. parts[0] = parts[0].padleft(4, '0'); // add new string result list. result.add(string.join(" ", parts)); } // otherwise keep line how is. else result.add(line); } // returns new list can formatted further. return result; } } }
right have save both text boxes .txt file before can 'upload' them final format button format , merge files. there anyway not have save files hardcopy rather upload them both formattedtextrichtextbox , formattedrefsrichtextbox processes more formatting?
i read in both files (maybe using file.readalllines()). give array lines in files. there, use linq select method project lines key value pairs (or that), maybe convert todictionary(). fancy joining , logic in memory , write out new file. code forthcoming (maybe)
edit: think generates output you're looking for.
string filemerger() { var file1 = file.readalllines(@"c:\....\file1.txt"); var file2 = file.readalllines(@"c:\....\file2.txt"); var file1lines = file1.select(f => f.split('\t')).todictionary(f => f[1], f => f); var file2lines = file2.select(f => f.split('\t')).todictionary(f => f[0], f => f[1].split(',')); stringbuilder newoutput = new stringbuilder(); foreach(var line in file1lines) { if(file2lines.containskey(line.key)) { newoutput.append(combine(line.value, file2lines[line.key])); } else { newoutput.appendline(string.join("\t", line.value)); } } return newoutput.tostring(); } string combine(string[] file1line, string[] file2line) { stringbuilder builder = new stringbuilder(); foreach(var str in file2line) { builder.appendline(string.format("{0}\t{1}\t{2}\t{3}\t{4}", file1line[0], str, file1line[2], file1line[3], file1line[1].endswith("a") ? "t" : "b")); } return builder.tostring(); }
Comments
Post a Comment