shell script to rename folder by info from file inside

423 Views Asked by At

well, I got a set of folders each containing a *.nfo file from XBMC (beside other files such as videos and pictures etc).

I want to rename the folder by strings inside the *.nfo file. The relevant content of such a *.nfo file:

...
    <title>Filmtitle</title>
...
    <year>2011</year>
...
    <director>Werner Herzog</director>
...

UPDATE: here is an unmodified, original .nfo file from XBMC

movie.nfo

I tried a lot with find exec and grep, but I did not really get anythin usable...

In the example above the folder should have the name "Filmtitel [2011, Werner Herzog]"

Maybe someone can help me out!

1

There are 1 best solutions below

4
On

Try the following script. It extracts the title, year and director from each file and then renames the directory:

find . -type f -name "*.nfo" -print0 | while IFS= read -r -d $'\0' file
do
    title="$(sed 's|.*<title>\(.*\)</title>.*|\1|g' $file)"
    year="$(sed 's|.*<year>\(.*\)</year>.*|\1|g' $file)"
    director="$(sed 's|.*<director>\(.*\)</director>.*|\1|g' $file)"

    dirName="${file%/*}"
    newDirName="${dirName%/*}/$title [$year, $director]"
    # mv "$dirName" "$newDirName"
    echo mv "$dirName" "$newDirName"
done

(Simply uncomment the mv command if you are happy that the commands being printed out are correct.)