nsmbrn
nsmbrn

Reputation: 3

text file manipulation in MATLAB

I have a text file which contain a combination of string and numbers. for example like following:

*Preprint, echo=NO, model=NO, history=NO, contact=NO

*Element, type=S4R

1, 1, 9, 189, 84

2, 9, 10, 190, 189

3, 10, 11, 191, 190

4, 11, 12, 192, 191

*Surface, type=ELEMENT, name=Surf-1

I like to remove >> 2, 9, 10, 190, 189 I mean I want to have following in a new file:

*Preprint, echo=NO, model=NO, history=NO, contact=NO

*Element, type=S4R

1, 1, 9, 189, 84

3, 10, 11, 191, 190

4, 11, 12, 192, 191

*Surface, type=ELEMENT, name=Surf-1

I should notice that these data are changed, and the only thing that I know about them is its number, for above example line 4.

I have googled many times to write a text file from another one by skipping from special line that I just know its number without much success!

any suggestion will be appreciated.

Upvotes: 0

Views: 88

Answers (1)

Coriolis
Coriolis

Reputation: 396

The fgets function allows you to read an ASCII file line by line. When you encounter the line you want to skip (knowing its number as you said) just use the continue statement to skip the iteration :

clc;
close all;
clear all;

input = fopen('input.txt','r');
output = fopen('output.txt','w');
line = fgets(input);
fprintf(output,'%s',line);
cpt=0;
offset = 3;

while ischar(line)
    cpt=cpt+1;
    if (cpt==offset) 
        line = fgets(input);
        continue;
    end
    line = fgets(input);
    fprintf(output,'%s',line);
end

fclose(input);
fclose(output);

The first fgets allows you to copy the first line from your input file in memory.

The following fprintf writes it into your output file.

Next you define a counter initialized to zero and you also define the offset, that is the line you want to skip minus 1 because you have already read the first line.

Then you use a WHILE loop in which you read each line from the input file with the fgets function and directly writes it into your output file. When you reach the end of the file, fgets return -1 which is not a character and so the loop ends.

You notice that cpt is iterated and if it equals the offset then you must skip the line, so you read it but you do not write it and the continue statement allows you to jump to the next iteration of the loop skipping the remaining instructions.

You can use fgetl instead of fgets if you want to get rid of newline characters.

The input file :

*Preprint, echo=NO, model=NO, history=NO, contact=NO

*Element, type=S4R

1, 1, 9, 189, 84

2, 9, 10, 190, 189

3, 10, 11, 191, 190

4, 11, 12, 192, 191

*Surface, type=ELEMENT, name=Surf-1

The output file :

*Preprint, echo=NO, model=NO, history=NO, contact=NO

*Element, type=S4R

1, 1, 9, 189, 84

3, 10, 11, 191, 190

4, 11, 12, 192, 191

*Surface, type=ELEMENT, name=Surf-1

Upvotes: 1

Related Questions