Erase whitspace and lowercase before hyphen - filename
I have a lot of text files that I rename in a specific format. Below I can remove spaces and make lowercase letters. However, this is not the desired result.
How could I format (strip out spaces and make lowercase letters) everything before the hyphen and then only take the first space after the hyphen?
find /temp/ -depth -name "* *" -type f -exec rename 's/ +\././; y/A-Z /a-z_/' {} +
Input result:
Hello Video - KEEP.txt
Output:
hello_video_-_keep.txt
Desired output:
hello_video_-KEEP.txt
source to share
If it was a file, I would use:
sed -re 's/^([^-]*)-\s*([^\.]*)/\L\1-\U\2/' -e 's/ /_/g' file
-
s/^([^-]*)-\s*([^\.]*)/\L\1-\U\2/
converts everything from the beginning of the file to a dash to lowercase-
. It is then converted to uppercase up to a dot. -
s/ /_/g
converts all spaces to underscores_
.
For your text, it returns:
hello_video_-KEEP.txt
If you want to keep the word as it is, from -
to .
, use \E
to recover. Then we can also get rid of the excess _-
by replacing it with just -
(a little ugly, I know).
$ cat file
Hello Video - KEEP.txt
My File - KeEp.txt
$ sed -re 's/^([^-]*)-\s*([^\.]*)/\L\1\E-\2/' -e 's/ /_/g' -e 's/_-/-/g' file
hello_video-KEEP.txt
my_file-KeEp.txt
As a reminder, these are the ways to change upper / lower case:
-
\L
- convert all subsequent characters to lowercase -
\U
- convert all valid characters to uppercase -
\E
- leave all valid symbols in their current case
How can you celebrate his work? Scroll through the command results find
:
while read -r file
do
new_file=$(echo "$file" | sed -re 's/^([^-]*)-\s*([^\.]*)/\L\1\E-\2/' -e 's/ /_/g' -e 's/_-/-/g')
echo "mv '$file' '$new_file'"
done < <(find . -type f ...)
For a given input, this will create this content:
mv './My File - KeEp.txt' './my_file-KeEp.txt'
mv './Hello Video - KEEP.txt' './hello_video-KEEP.txt'
once you are sure that it works, just remove echo
and use mv
. Please note that quotes are required! Otherwise, it will not handle spaces in filenames correctly.
source to share