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?
The problem comes from the fact that you are using
lstogether 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 withI 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
or (to include hidden files)
The
-1ensures that the filenames are output at the start of the line. Without this option,lswould prepend each file name with a single space.