I have some folders with \n
character it their names.
for example:
$ ls
''$'\n''Test'
Thats refer to a folder with Test name and a empty line before its name.
So when I run some scripts like this, in its parent directory:
while IFS= read -r d; do
rmdir $d
done < <(find * -type d)
It shows:
rmdir: failed to remove '': No such file or directory
rmdir: failed to remove 'Test': No such file or directory
Because it runs twice, once on \n
and the another on Test
, because the folder name has two lines.
So how can I solve this issue such that, script knows \nTest
is just one folder?
Best Answer
You've only single command there, so it's sufficient to call
find
with-exec
flag callingrmdir
:Or use the
-delete
option as infind -type d -delete
, but it won't work with non-empty directories. For that you will also need-empty
flag. Note also,-delete
implies-depth
so that may be skipped. Thus another viable alternative that keeps everything as one process:If the directory not empty, use
rm -rf {} \;
. To isolate only directories with\n
in filename we can combine bash's ANSI-C quoting$'...'
with-name
opption:POSIX-ly, we could handle it this way:
It is worth mentioning that if your goal is removal of directories, then
-delete
is sufficient, however if you want to execute a command on directory then-exec
is most appropriate.See also
find
output?