Xman Blog Inside

Wednesday, August 23, 2006

Using BASH to print/manipulate all files in a directory

There are two files in my tmp directory.
xman@sai tmp $ ls
file1.txt file version 2.txt
You are probably familiar with simple for-loop in BASH script. But, see the following:
xman@sai tmp $ for i in `ls`
> do
> echo $i
> done
file1.txt
file
version
2.txt
xman@sai tmp $
Opssss, it doesnt print out each of the file names properly when there is space characters in the file names. The file names will be broken when there are spaces. Instead, you probably want to do the following:
xman@sai tmp $ export IFS=$'\n'
xman@sai tmp $ for i in `ls`
> do
> echo $i
> done
file1.txt
file version 2.txt
xman@sai tmp $
So now you can manipulate each of the files in a directory properly.

2 Comments:

  • At 8/24/2006 9:22 PM , Anonymous Anonymous said...

    Perhaps a simpler approach is:

    for i in * ; do echo $i ; done

     
  • At 8/24/2006 9:52 PM , Blogger xman said...

    Thanks Chris. Didnt know I can simply do that. Perhaps if you are doing more than an echo e.g. mv, then "$i" is needed instead of simply $i. Alternatively, if we had set IFS=$'\n', then we dont need the "". ;) Correct me if I'm wrong.

     

Post a Comment

Subscribe to Post Comments [Atom]

<< Home