List file using ls with a condition and process/gr

2019-08-16 01:16发布

问题:

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'


标签: bash ls