Perl can make quite a useful addition to bash. Typically, sed would be used to massage strings; however, the regular expressions support in perl is more flexible. Say we have a directory with a bunch of files similar to this:
[u-1@srv-1 ~/bp]$ ls april04stuff.html april14stf.html jl11stuff.html may12stf.html may13stf.html |
We decide that we want all files to start with the day digits, that the month part should be after, and that everything after the month part should just be stuff. With a little perl bashing:
[u-1@srv-1 ~/bp]$ for i in * > do t=$(echo $i| perl -pe "s/(\D*)(\d*)\D*\.html\$/\$2\$1\stuff.html/g") > cp $i ../bp2/$t > done [u-1@srv-1 ~/bp]$ ls ~/bp2/ 04aprilstuff.html 11jlstuff.html 12maystuff.html 13maystuff.html 14aprilstuff.html [u-1@srv-1 ~/bp]$ |
D matches non digits. d matches digits. The stuff inside the parenthesis is used for $1 and $2, which lets us switch the parts around. We used cp in this example, but mv would work just as well. With the addition of perl, there are many possibilities. Note that we had to escape stuff like the $ to make this work. Please do make backups before you go running scripts like this. 🙂