필터 지우기
필터 지우기

How to remove lines that do not start with specific characters?

조회 수: 8 (최근 30일)
Sharen H
Sharen H 2013년 1월 2일
The file consists of values like
v 1 2 3
v 1 2 3
vt 1 2 3
vn 1 2 3
f 1 2 3
I want only lines that start with v or f -- other lines should be removed .
How to do this? Please help me. Thanks in advance.
Is it possible using this regexprep?

답변 (2개)

Sriram
Sriram 2013년 1월 2일

Walter Roberson
Walter Roberson 2013년 1월 2일
infile = fileread('YourFileName.txt');
newfile = regexprep(infile, '^[^vf].*$', '', 'lineanchors', 'dotexceptnewline');
fid = fopen('NewFileName.txt');
fwrite(fid, newfile);
fclose(fid)
  댓글 수: 3
Walter Roberson
Walter Roberson 2013년 1월 2일
All the lines you show in your sample begin with either 'v' or 'f'. A line that starts with 'vn' still starts with 'v'.
What you probably want is
infile = fileread('YourFileName.txt');
newfile = regexp(infile, '^[vf]\s.*$', 'match', 'lineanchors', 'dotexceptnewline')
fid = fopen('NewFileName.txt', 'wt');
fprintf(fid, '%s\n', newfile{:});
fclose(fid);
YourFileName.txt and NewFileName.txt should be replaced by the actual input file name, and the actual name of the new file you want.
The regexp expression here means to look for input lines in the string "infile" that start with the letter v or f, followed by whitespace, and then anything until the end of the line, and copy those lines to the cell array of strings "newfile".
Jan
Jan 2013년 1월 2일
@Sharen: Please do not post "not working" without any explanations in the forum. Do you get an error message (which one?) or do the results differ from your expectations (how?)?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by