Reputation: 43
I am a complete newbie to Linux (I am using Linux Mint) and I need your help understanding basic bash commands.
I store my files on an external hard drive (NTFS formatting) that I use in different OS. My files are organized in many directories (folders) and inside each primary directory I have more folders and inside those folders I have other folders and so on. I need a bash command to find all the directories with trailing spaces at the end of each name. If possible, I would also like to use a bash command to remove the blank space(s). I have tried looking into other answers but I only find the commands and no clear explanation of what they do, so I am not sure whether that is what I am looking for and I don’t want to risk changing something inadvertently. Any help explaining which commands to use would be greatly appreciated!
Upvotes: 4
Views: 2813
Reputation: 338
find . -name "* " -type d
.
searches current directory and subdirectories.
-name
searches for filenames that match (asterisk means match zero more characters, the literal space matches a space at the end of the filename)
-type d
searches for items of type directory.
Upvotes: 3
Reputation: 295279
The following is written to be easy-to-follow (as a secondary goal), and correct in corner cases (as a primary goal):
# because "find"'s usage is dense, we're defining that command in an array, so each
# ...element of that array can have its usage described.
find_cmd=(
find # run the tool 'find'
. # searching from the current directory
-depth # depth-first traversal so we don't invalidate our own renames
-type d # including only directories in results
-name '*[[:space:]]' # and filtering *those* for ones that end in spaces
-print0 # ...delimiting output with NUL characters
)
shopt -s extglob # turn on extended glob syntax
while IFS= read -r -d '' source_name; do # read NUL-separated values to source_name
dest_name=${source_name%%+([[:space:]])} # trim trailing whitespace from name
mv -- "$source_name" "$dest_name" # rename source_name to dest_name
done < <("${find_cmd[@]}") # w/ input from the find command defined above
See also:
while read
loop's syntax in general, and the purposes of the specific amendments (IFS=
, read -r
, etc) above.${var%suffix}
syntax, known as "parameter expansion", used to trim a suffix from a value above).find
and its integration with bash.Upvotes: 9