- starting with the literal TABLE:
- plus one or more + white space(s) \s
- plus the literal "MASS SOURCE"
- plus as few characters as possible .*? (lazy quantifier, when the greedy version .* means as many as possible)
- and then followed by (but not replaced, it's a look forward (?=...) ) one or more carriage return or line feed |[\r
How Can I replace specific lines in a text file
29 views (last 30 days)
I'm dealing with text files and I want to replace certain lines in the text. I do not know their location but I know the text in an above and a later line to those lines.
Example for that text
TABLE: "LINK PROPERTY DEFINITIONS 02 - LINEAR" Link="Rails Pinned" DOF=U1 Fixed=Yes Link="Rails Pinned" DOF=U2 Fixed=Yes
TABLE: "MASS SOURCE" MassSource=MSSSRC1 Elements=Yes Masses=Yes Loads=No IsDefault=Yes
TABLE: "MATERIAL PROPERTIES 04 - USER STRESS-STRAIN CURVES" Material="Timber Ties" Strain=-0.00078125 Stress=-1
I would like to replace the line/lines after TABLE: "MASS SOURCE" and before the following word TABLE: The word table repeats many times in the original text and because of that I need the following word TABLE: Is it possible?
Cedric Wannaz on 22 Sep 2017
Edited: Cedric Wannaz on 22 Sep 2017
Here is an example, but we can be much more specific.
% - Read source.
content = fileread( 'myData.txt' ) ;
% - Update.
content = regexprep( content, 'TABLE:\s+"MASS SOURCE".*?(?=[\r\n]+TABLE)', 'Hello World' ) ;
% - Export update.
fId = fopen( 'myFile_updated.txt', 'w' ) ;
fwrite( fId, content ) ;
fclose( fId ) ;
where we use a regular expression for pattern matching. The call is
newContent = regexprep( oldContent, pattern, replacement ) ;
and the pattern matches a string