I have a list of files in a folder which some of the files have spaces in the filename.
I need to replace the whitespace with _ but first, i need to list the file with condition ls *_[1-4]*[A-c]*
. After filter the files, some of the files have whitespace with no fixed position(front, middle, end position).
How can i replace the whitespace after ls command?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
You don't want to process the output from ls
. Simply loop over the matching files.
for file in *_[1-4]*[A-c]*; do
# Skip files which do not contain any whitespace
case $file in *\ *) ;; *) continue;; esac
echo mv -n "$file" "${file// /_}"
done
The echo
is there as a safeguard; take it out if the output looks correct.
The case
and the substitution looks for a space (ASCII 32); if you also want to match tabs, form feeds, etc, adapt accordingly. bash
allows for something like $[\t ]
to match a tab or space, but this is not portable to other Bourne shell implementations
回答2:
I would use find
to list the files and pipe to the results to sed
:
find -maxdepth 1 -type f -name '*_[1-4]*[A-c]*' | sed 's/ /_/g'