'ls' question, splitting and files with spaces in their name...
Tim Writer
tim-s/rLXaiAEBtBDgjK7y7TUQ at public.gmane.org
Sun May 23 15:10:56 UTC 2004
James Knott <james.knott-bJEeYj9oJeDQT0dZR+AlfA at public.gmane.org> writes:
> Madison Kelly wrote:
> > Hi all,
> > I need to read in the results of an 'ls' call to a bunch of variables (in
> > Perl) and I am doing so like this:
>
> > =- Snip
>
> > open (LS, "ls -lA '$mnt_dir' 2>&1 |");
> > while (<LS>)
> > {
> > s/\n//;
> > # The first $perm will be "total"
> > ($perm, $num, $owner, $group, $size, $month, $day, $time_year,
> > $file)=split/\s+/;
>
> > =- Snip
> > My problem is that I am just straight splitting on spaces and some files
> > and directory names have spaces in them. I read the 'ls' man page and the
> > closest thing I could find was a switch to add an escape character before
> > the space but that would only be marginally helpful.
>
> > What I need is some way to show the file or directory name with some
> > other character instead of a space so that the first split will leave the
> > file or directory name intact wherein after I could substitute the space
> > back.
>
> > Anyone have any ideas that might help?
>
> > The only thing I can think of is to add a whole bunch of $file1, $file2,
> > $file3, ... $file# and then splice them back together but that would be
> > cumbersome and also create a limit on the number of spaces that could be in
> > a file name (and risk missing those above that).
>
>
>
> Perhaps I'm missing something, but it doesn't seem like there's much of a
> problem, if you approach it in the right way. If you do a "ls -lA", you'll
> notice that the file or directory is always the last item, on a line with a
> fixed number of items. Why not just pull off the first eight items, using
> the space separator and take the rest of the line as the file or directory
> name?
Good advice but I'm a little surprised nobody mentioned readdir and stat.
In other words, rewrite it (without ls) like this:
opendir(DIR, $mnt_dir) or die "Can't open $mnt_dir: $!";
for (readdir(DIR)) {
($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
$atime,$mtime,$ctime,$blksize,$blocks) = stat($_);
}
closedir(DIR);
You get all the same information from stat that you got from "ls -l" but in a
slightly different form and spaces are handled automatically. In addition,
you don't have the overhead of running ls in a separate process.
--
tim writer <tim-s/rLXaiAEBtBDgjK7y7TUQ at public.gmane.org> starnix inc.
905.771.0017 ext. 225 thornhill, ontario, canada
http://www.starnix.com professional linux services & products
--
The Toronto Linux Users Group. Meetings: http://tlug.ss.org
TLUG requests: Linux topics, No HTML, wrap text below 80 columns
How to UNSUBSCRIBE: http://tlug.ss.org/subscribe.shtml
More information about the Legacy
mailing list