As a follow-up to my previous question, if I have multiple files of the form
sw.ras.001 sw.ras.002 sw.ras.003 …
What command can I use to remove the ras. in the middle of all the files?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can do this with a fairly small modification of either answer from the last question:
rename s/ras.// sw.ras.*
or
for file in sw.ras.*; do
mv "$file" "${file/ras./}"
done
Explanation:
rename is a perl script that takes a perl regular expression and a list of files, applies the regex to each file’s name in turn, and renames each file to the result of applying the regex. In our case, ras is matched literally and . matches a literal . (as . alone indicates any character other than a newline), and it replaces that with nothing.
The for loop takes all files that start with sw.ras. (standard shell glob) and loops over them. ${var/search/replace} searches $var for search and replaces the first occurrence with replace, so ${file/ras./} returns $file with the first ras. removed. The command thus renames the file to the same name minus ras.. Note that with this search and replace, . is taken literally, not as a special character.
Method 2
Another option is to use mmv (Mass MoVe and rename):
mmv '*ras.*' '#1#2'
Don’t forget to use the single quotes around your patterns, otherwise the stars will be expanded at the shell level.
The utility is not always available but if it’s not, you can install it with:
sudo apt-get install mmv
See the man page here.
Method 3
In any POSIX-compliant shell (bash, dash, ksh, etc):
for file in sw.ras.[[:digit:]][[:digit:]][[:digit:]]; do
mv "${file}" "${file/ras./}"
done
Or with rename:
rename 's/ras.//' sw.ras.[[:digit:]][[:digit:]][[:digit:]]
Method 4
I recently had to do a bulk rename of a number of files where I had to replace the last occurrence of a character where the character occurred multiple times in the filenames. In this particular case I had to replace the last dash - with an underscore _, turning this:
some-long-file-name.ext
into this:
some-long-file_name.ext
It took some time but this finally did it:
for FILE in *; do mv $FILE ${FILE%-*}_${FILE##*-}; done
Here:
${i%-*}matches the begining of the filename up to the last occurrence of the dash-${file##*-}matches the rest of the filename after the last occurrence of the dash-
Method 5
Using find, xargs and sed:
find -name 'sw.ras.*' -print0 | sed -ze "p;s/.ras//" | xargs -0 -n2 mv
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0