I am passing a filename into my bash script and cleaning the name using sed. A few sample files would be:
Test 01.txt
Test v2 01.txt
I would
Instead of
sed -r -e 's/\d+/sprintf("%03d",$&)/e'
use
perl -pe 's/\d+/sprintf("%03d",$&)/ge'
Per your comment, yes I understand about debugging with that method, and that was my guess.
It's almost as easy, and doesn't require a cleanup step later on to move the closing lines and the "'" char up and down a list like below to debug (as an alternative solution).
j=$(
echo "$j" \
| sed '
s/\///g
s/_/ /g
s/^\.//
s/\[[^()]*\]//g
s/([^()]*)//g
s/#//g
s/+/\ /g
s/\.\././g
s/\&/and/g
s/\ -/-/g
s/-\ /-/g
s/-{2,}/-/g
s/\.\././g
s/'"'"'//g
s/ {2,}/ /g
s/\ \././g
' \
| awk '/[0-9]/{
match( $0,/[0-9][0-9]*/ )
begin=substr($0,1,RSTART); end=substr($0,RSTART+RLENGTH,length($0))
num=substr($0,RSTART,RSTART+RLENGTH)
printf("%s%03d%s", begin,num+0, end)
}'
)
Edit It may be possible to double-triple up on the escaped single quotes, i.e. \\'
or \\\'
, but I'm going with the tried and true s/'"'"'//g
.
Unless you're using the original bourne shell on Solaris, AIX, HP, or other old-line unixen, join the 1990s ;-) and use the $( ...)
construct for command substitution. Backquotes have been deprecated since at least 'The New Kornshell programming Language', published 1995.
I hope this helps.
This might work for you (GNU sed):
sed -r 's/[0-9]+/$(printf "%03d" &)/g;s/.*/echo "&"/e' file
Test 001.txt
Test v002 001.txt