I have a bucket on GCP cloud storage and I want to rename all files that have a white space in their filename to the name where the whitespace is removed by a hyphen (-).
I tried something like
gsutil ls gs://<bucket>/<folder_with_the_files_to_rename>/ | sed 's/ /-/g/gsutil mv & \1/'
Unfortunately, I cant get the sed command work to replace the whitespace and then use the gsutil mv command to actually rename the file.
Can someone help me?
If you need to replace any space with -
in some file names that you get with gsutil ls gs://<bucket>/<folder_with_the_files_to_rename>/
, you can use
gsutil ls gs://<bucket>/<folder_with_the_files_to_rename>/ | \
while read f; do
gsutil -m mv "$f" "${f// /-}";
done;
gsutil mv
command moves/renames files, and ${f// /-}
is a variable expansion syntax where each space is replaced with -
(the //
stands for all occurrences). Thus, you do not need sed
here.
Once small change request.
gsutil
is listing files in Cloud Storage. Your move statement is moving files on local storage.I think so. I plan to try your example this weekend. Your renaming expression is very cool. I use
sed
andregex
a lot and this goes on my expert's list.The problem i have: If I execute the command
$(gsutil ls gs://<bucket>/<folder_with_the_files_to_rename>/)
just like that (in the terminal directly or in a sh file) it returns as @John Hanley described the whole object name with the parent path. e.g. gs://<bucket>/<folder_with_the_files_to_rename>/file1.txt gs://<bucket>/<folder_with_the_files_to_rename>/file 2.txt Even if there is a white space it is one object. SEE NEXT COMMENTTry
while read -r f; do gsutil -m mv "$f" "${f// /-}"; done < <(gsutil ls gs://<bucket>/<folder_with_the_files_to_rename>/)
@nikos Great, I updated the answer.