Reputation: 1190
I am renaming files and directories. Basically, all I want to do is strip out spaces and replace them with underscores and finally make lower case. I could do one command at a time: $ rename "s/ /_/g" *
, then the lower case command. But I am trying to accomplish this all in one line. Below all I am able to accomplish is strip out the spaces and replace with _
but it doesn’t make lower case. How come?
find /temp/ -depth -name "* *" -execdir rename 's/ /_/g; s,,?; ‘
Original file name:
test FILE .txt
Result: (If there is a space at the end, take out)
test_file.txt
Upvotes: 5
Views: 4148
Reputation: 26066
While the original question mentions using rename
explicitly, I am using macOS which does not have rename
installed by default.
So instead I created this find
script that uses the one-liner that Kristijan Iliev posted previously in their 2014 answer. It uses tr
and sed
so it is more portable across different Linux-like operating systems.
This simple script will rename relevant filenames in the current working directory; change the .
to match a file path if desired.
find . -depth -name "* *" -type f |\
while read source_filepath
do
destination_filepath=$(echo "${source_filepath}" | tr A-Z a-z | tr -s ' ' | tr ' ' '_'| sed 's/_\./\./');
mv -f "${source_filepath}" "${destination_filepath}";
done
Upvotes: 0
Reputation: 4987
Try this line:
echo "test FILE .txt" | tr A-Z a-z | tr -s ' ' | tr ' ' '_'| sed 's/_\./\./'
Upvotes: 1
Reputation: 113834
rename 's/ +\././; y/A-Z /a-z_/'
Or, combined with find
:
find /temp/ -depth -name "* *" -exec rename 's/ +\././; y/A-Z /a-z_/' {} +
To target only files, not directories, add -type f
:
find /temp/ -depth -name "* *" -type f -exec rename 's/ +\././; y/A-Z /a-z_/' {} +
Would it be possible to rename the file with the last three characters of the original file for example from big Dog.txt to dog.txt?
Yes. Use this rename
command:
rename 's/ +\././; y/A-Z /a-z_/; s/[^.]*([^.]{3})/$1/'
Upvotes: 5