How to delete lines before a particular character from .txt files?

I have 100 files. I want to delete the lines before the word 'pressure' from all the files. The number of lines before the word 'pressure' is different in different files. A sample file if attached. Thanks in advance.

Risposte (2)

Stephen23
Stephen23 il 10 Nov 2018
Modificato: Stephen23 il 10 Nov 2018
A straight-forward line-by-line method:
[fii,msg] = fopen('tdump18020910.txt','rt');
assert(fii>=3,msg)
[fio,msg] = fopen('tdump_new.txt','wt');
assert(fio>=3,msg)
boo = false;
while ~feof(fii)
str = fgetl(fii);
boo = boo || ~isempty(strfind(str,'PRESSURE'));
if boo
fprintf(fio,'%s\n',str);
end
end
fclose(fii);
fclose(fio);
The input and output files are attached. Too loop over multiple files simply use one of the two methods given in the MATLAB documentation:
For example, using dir:
S = dir('*.mat);
for k = 1:numel
F = S(k).name;
... remove lines
end

2 Commenti

Thank you for your response. I want this change in the input file(s). Is it possible to do so?
"I want this change in the input file(s). Is it possible to do so?"
It is not very clear what you are asking, but I suspect that you want to apply this code to multiple files automatically, in which case the answer is: read the last part of my answer and the link that I gave. you to read

Accedi per commentare.

File = 'tdump18020910.txt';
Str = fileread(File);
CStr = splitstr(Str, '\n');
match = find(contains(CStr, 'PRESSURE', 'IgnoreCase', true), 1);
[fid, msg] = fopen(File, 'w');
if fid < 0, error('%s', msg); end
fprintf('%s\n', CStr{match:numel(CStr)});
fclose(fid);

Categorie

Tag

Richiesto:

il 10 Nov 2018

Risposto:

Jan
il 13 Nov 2018

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by