How can I change the file extension recursively in GNU / Linux?

2

I'm trying to get all the .sql files from my project and change the extension to .md .

I've already been able to do this, however, the files are being moved to the root of the system, which is the path where the shell script is. How to rename keeping the original file in the same directory?

#!/bin/bash

shopt -s globstar
for file in ./**/*.sql; do
    mv "$file" "$(basename "$file" .sql).md"
done
    
asked by anonymous 21.11.2018 / 14:03

2 answers

2

You could probably use $(dirname $file) to get the folder path of the current file in the loop

for file in ./**/*.sql; do
    mv "$file" "$(dirname "$file")/$(basename "$file" .sql).md"
done
    
21.11.2018 / 14:17
2

The problem is that basename takes the information out of the folder and returns only the file name. So the idea is not to use it, so this information is not lost.

To manipulate the filename, you can use the ${var%pattern} syntax, remove pattern from the value of var :

for file in ./**/*.sql; do
    mv $file "${file%.sql}.md"
done

${file%.sql} removes the ".sql" strand from the file name and then .md adds this string to the name. That is, the extension is changed from .sql to .md .

    
21.11.2018 / 14:16