[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Maybe offtopic: Dealing with filenames with blanks in a script



Once upon a time diego said...
> 
> I'm trying to manage files that have one or more blanks in their names
> [...] 
> I want a script to do some processing on them, let's simplify with a
> simple cat:
> 
> for i in `ls *`; do cat $i; done

Never use `ls *`, when a simple * will do.  eg: 
  for i in * ; do cat $1; done

Using `ls *` is causing the first of your problems, namely defining
filename boundaries - you are losing them with `ls *`.

Once you've properly globbed, always surround variable expansion with
double quotes:
  for i in * ; do cat "$1" ; done

This will keep the filename together when passed on the command line to
another command (cat in this case). cat will not see the filename as two
(or more) filenames.

In any script you write, if a variable holds a filename it is always a
good idea to enclose the expansion in double quotes.

Sometimes you want to operate recursively on a set of files, where the
directories or filename will have spaces in them. In that case, using
the -print0 command to find(1) and the -0 option to xargs(1) gets around
the problems. eg:

  find . -print0 | xargs -0 cat

The -print0 and -0 command line options tell find and xargs to use
null-terminated strings, not space terminated words.



Reply to: