Skip to Content

Using BASH to print/manipulate all files in a directory

Posted in

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.

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.