List file using ls with a condition and process/grep files that only whitespaces

二次信任 提交于 2019-12-12 03:29:35

问题


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'


来源:https://stackoverflow.com/questions/37984665/list-file-using-ls-with-a-condition-and-process-grep-files-that-only-whitespaces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!