Find and replace empty element in text file

1 view (last 30 days)
Dung Tran
Dung Tran on 24 Mar 2021
Commented: Dung Tran on 25 Mar 2021
Hi everyone,
I have a Text file *txt with content example with row and columm below:
1234 5678 2a13 31424 1234a 12455
1245 4353 4143 12434
11111 22222
12131 1321 1232 1213 12224
33333
12314 1434 31231 3123 2131 13213
As we can see:
  • second row has 2 empty element from last 2 column, but these empty suppose to have the data which is the element from the first 2 columm at 3rd row ( 11111 22222) .
  • 4th row has missing last element which suppose to be the data 33333 in 5th row.
I want to move the 11111 22222 back to the last 2 column at 2nd row, and 33333 moved back to last columm at 4th row as below:
1234 5678 2a13 31424 1234a 12455
1245 4353 4143 12434 11111 22222
12131 1321 1232 1213 12224 12424
12131 1321 1232 1213 12224 33333
12314 1434 31231 3123 2131 13213
the File have thousand of row with thousand of row and 6 columm, and it have many rows that have errors like this. are there a good way to handle this issue, i guess we can use loop for this problem, but if anybody have any other idea please just show to me. Thank you very much.

Answers (1)

Jan
Jan on 24 Mar 2021
S = fileread(FileName);
S = strrep(S, char(13), '');
S = strrep(S, char(10), ' ');
C = strsplit(S, ' ');
C = strrep(C, ' ', ''); % Just to be sure
FID = fopen(FileName_2, 'w');
if FID == -1, error('Cannot open file for writing: %s', FileName_2); end
fprintf(FID, '%s %s %s %s %s\n', C{:});
fclose(FID);

Categories

Find more on Data Import and Export 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!