Search code examples
bashls

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


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?


Solution

  • 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