How Can I replace specific lines in a text file
4 ビュー (過去 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!