How to create a text file from grep output

10 Ansichten (letzte 30 Tage)
Zoe Watson
Zoe Watson am 10 Feb. 2015
Beantwortet: dpb am 10 Feb. 2015
I have a data file which looks like this:
Input
x y z coulomb normal shear
(km) (km) (km) (bar) (bar) (bar)
-30 -30 2.5 0.0 0.0 0.0
-30 -29 2.5 0.1 0.1 0.1
I would like to remove the first three lines, so I just have a file full of numbers, and then create a new file with this data. If I was working in Unix, the command would be as follows:
grep -v -e Input -e x -e (km) filename.txt > newfilename.txt
Matlab has a grep function, but I can't work out how to generate a new file with the output from grep.

Antworten (2)

Guillaume
Guillaume am 10 Feb. 2015
Matlab does not have a grep function (according to my docs). It's a fairly simple function to write anyway:
function skipcopy(origfile, newfile, skip)
%origfile: full path of file to crop
%newfile: full path of cropped file to create
%skip: number of initial line to skip:
fidin = fopen(origfile, 'rt');
if fidin == -1
error('failed to open %s', origfile);
end
fidout = fopen(newfile, 'wt');
if fidout == -1
error('failed to create %s', newfile);
end
for s = 1:skip
fgetl(fidin);
end
fwrite(fidout, fread(fidin));
end

dpb
dpb am 10 Feb. 2015
If that's the way you're intent on going about it, just use the bang operator "!" and submit the command to the OS. There are Windows grep's easily available.
But, in Matlab it's simpler to just use the i/o functions imo...
x=importdata('filename.txt'); % it'll find the header on it's own and return the numeric
dlmwrite('aknew.dat',x(1:5,:),'delimiter',' ','precision','%.2f') % write with 2 decimals
If you must have the precision as shown then need to use format string and fprintf

Kategorien

Mehr zu File Operations finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by