Create a script rename1.sh:
#! /bin/bash
old=$1
new=${old//[\''"?*%#^!@$&()=+[]{};,`~']}
new=${new//['<>:\|']/-} # I removed /, see below.
if [[ -e $new ]] ; then
if [[ $old != $new ]] ; then
echo Cannot rename "$old" to "$new" - target already exists.
fi
else
mv "$old" "$new"
fi
It renames one file according to the given rules using parameter expansion. To rename a subtree, run it with find
:
find /path -exec rename1.sh {} \;
Are you sure you want to replace /
with -
? It would put all the files into the same directory.
printf and overwriting with carriage return
This type of "magic" can be done via printf
and carriage return "\r" to overwrite existing output. However, you will have to be conscious for consecutive lines. Observe this example:
#!/bin/bash
string="[ ] pinging google.com "
printf "%s" "$string"
if ping -c 4 -q google.com > /dev/null
then
printf "\r[OK"
printf "\n\n"
fi
Notice how we have the "status" string print first, then we use carriage return to jump back to the beginning and overwrite first 3 characters with "[OK" string. The following two newlines is just example of what you'd want to do to move the script onwards and print more lines. As for the if command ; then . . . fi
, this is simple structure which executes body of if statement conditionally , depending on command
output.
Disadvantage of this approach is that if you don't match the character lengths of what you're printing, then it might show through.
$ printf "Hello\rcat\n"
catlo
Slightly better approach: clearing the line with escape code
We can take advantage of ANSI escape code for clearing line (in this case, in octal \033[2K
) for getting rid of what we previously had on the line. This has advantage of not running out in the issue of matching/not-matching length of what you print when you reset the cursor back to the beginning.
Here's an example, with added UTF-8 characters for check and cross-mark
#!/bin/bash
string="[ ] pinging google.com "
printf "%s" "$string"
if ping -c 4 -q google.com > /dev/null
then
# clear previous line, add UTF checkmar to string
printf "\r%b" "\033[2K"
string="[\U2713] pinging google.com "
else
# clear previous line, add UTF checkmar to string
printf "\r%b" "\033[2K"
string="[\U274C] pinging google.com "
fi
printf "%b" "$string"
Best Answer