How Can I replace specific lines in a text file
5 次查看(过去 30 天)
显示 更早的评论
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 个评论
Cedric
2017-9-22
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.
采纳的回答
Cedric
2017-9-22
编辑:Cedric
2017-9-22
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Data Preparation 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!