I have a txt file (ANSYS 1ST principle nodal stress list) and there are almost 16k lines inside of it. I wanna delete specific lines for example 1st, 2nd, 3rd, 4th, 5th, 39th, 40th, 41th, 42th, 43th, etc. I dont need to search anything, i know which lines be deleted. is there anybody help?
Asked
Active
Viewed 629 times
1
-
Please share your code – jrswgtr Jan 05 '19 at 11:29
-
Did you see this ? https://www.mathworks.com/matlabcentral/answers/159783-how-to-delete-specific-lines-from-a-txt-file – Mohammadreza Khatami Jan 05 '19 at 11:32
-
@MohammadrezaKhatami, that code does not work to my problem – Peyman Azimi Jan 05 '19 at 13:07
3 Answers
1
Maybe not the most efficient way but this works:
data_file = 'data.txt';
lines_to_skip = [1:5, 39:43];
fid = fopen(data_file);
ii = 0;
while ~feof(fid)
ii = ii + 1;
file_content{ii} = fgetl(fid);
end
lines = true(1,ii);
lines(lines_to_skip) = false;
fid = fopen(data_file,'w');
fprintf(fid,'%s\r\n',file_content{lines});
fclose(fid);

Jakob L
- 196
- 6
0
This is tagged as Matlab, but doing this inside Matlab is going to be painful because it doesn't usually offer a convenient way to remove bytes in the middle of a file, so you'd have to write some code to write the text to a new file, skipping lines as appropriate.
If you're on a UNIX system it'll be much easier using sed. There's a great answer here explaining how to do that. The key command is:
# To delete line 10 and 12:
sed -i -e '10d;12d' your-file.txt

Mark Ormesher
- 2,289
- 3
- 27
- 35