Reputation: 11
I try to print and manipulate all filenames in current directory and there are some filenames containing whitespace. But when I use IFS=$'\n’
to delimite filenames, it also remove character "n" from filenames.
Here is my code
#!/bin/dash
IFS=$'\n'
for file1 in $(ls)
do
echo "$file1"
done
It should print
apple.txt
different.txt #
empty.txt
hello word.txt
ifstest.sh
one.txt #
same.txt
But the result is
apple.txt
differe #
t.txt #
empty.txt
hello word.txt
ifstest.sh
o #
e.txt #
same.txt
What should I do to avoid that?
Upvotes: 1
Views: 464
Reputation: 22225
The problem comes from the fact that you are using ls
together with the loop.
If you don't need hidden files (i.e. those where the name starts with a .
to be included), you can achieve your goal with
for file1 in *
do
echo "$file1"
done
I assume that you want to do more processing with the file than just writing its name to stdout, because if you want to do the latter, you could do without a loop and simply write
ls -1
or (to include hidden files)
ls -1A
The -1
ensures that the filenames are output at the start of the line. Without this option, ls
would prepend each file name with a single space.
Upvotes: 1