How Can I replace specific lines in a text file
4 views (last 30 days)
Show older comments
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?
Thank you
2 Comments
Cedric
on 22 Sep 2017
What do you want to replace? There are plenty of tools for doing this, but we need to know exactly what you need to achieve. The best is to give a slice of this file with a few occurrences of what you need to replace, and to give an example of output after replacement.
Accepted Answer
Cedric
on 22 Sep 2017
Edited: Cedric
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
- 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
7 Comments
More Answers (0)
See Also
Categories
Find more on Text Data Preparation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!