How to change the file extension recursively in GNU/Linux?

Asked

Viewed 210 times

2

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

I’ve been able to do this, however, the files are being moved to the system root, 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
  • Has the command rename also, take a look https://www.computerhope.com/unix/rename.htm

2 answers

2

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

To manipulate the file name, you can use the syntax ${var%pattern}, that removes the Pattern of the value of var:

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

${file%.sql} removes the ". sql" snippet from the file name and then .md adds this string to the name. That is, the extension is replaced by .sql for .md.

2


Probably could use $(dirname $file) to take the path of the current file folder in the loop

for file in ./**/*.sql; do
    mv "$file" "$(dirname "$file")/$(basename "$file" .sql).md"
done
  • Top, would it also be possible to consider more than one extension? Type, apply the same rule (condition) to extension .sql, .pl and .txt?

  • @Fábiojânio In this case, you could do another for external with the extensions (for ext in .sql .pl .txt; do (faz o for acima com $ext))

  • Dear @Fábiojânio has yes, but then the subject is different, it would be nice to create a question just for this new specific doubt.

  • @Guilhermenascimento made a "cat" here and I think it worked: for file in ./**/*.sql ./**/*.ora; do
 mv "$file" "$(dirname "$file")/$(basename "$file" ."${file##*.}").md"
 # mv $file "${file%.sql}.md"
done

Browser other questions tagged

You are not signed in. Login or sign up in order to post.