Home » Questions » Computers [ Ask a new question ]

Is there a linux command like mv but with regex?

Is there a linux command like mv but with regex?

For example I want to mv (.*?).sql $1.php,

Asked by: Guest | Views: 224
Total answers/comments: 3
Guest [Entry]

"As others have mentioned, rename is good at this, but read the man page (man rename) before you try it. There are at least two entirely different tools out there called rename and which one you have will depend on your distribution. Calling them incorrectly can be dangerous.

Here's the man page for the perl-based version by Larry Wall that ships with Ubuntu. You give it a perl expression like rename 's/\.sql$/.php/' *.sql

Here's the man page for the rename that ships with older Red Hat and CentOS distributions. Usage is simple string substitution like rename .sql .php *.sql

You could also use a bash one-liner to process each file one at a time:

$ for f in *.sql; do mv -i ""$f"" ""${f%%.*}.php""; done"
Guest [Entry]

"G'day,

You could also try entering

for i in $(\ls -d *.sql)
do
mv $i $(echo $i | sed -e 's/\.sql$/\.php/')
done

Or to make it use regex's change it slightly to

for i in $(\ls -d | egrep -e '.*\.sql')
do
mv $i $(echo $i | sed -e 's/\.sql$/\.php/')
done

for a bit of shell coding fun. (-:"
Guest [Entry]

"Yes, mvregex does exactly this. github.com/nathanshearer/mvregex
I wrote it a while ago and use it frequently to fix problematic files. It is implemented in Bash so it is portable with minimal dependencies. It even works in cygwin which allows you to rename files with trailing spaces when the entire windows GUI, command line, and powershell will refuse to interact with said files."