Bash and Windows batch script file name variable conversion

I’ve been getting into Bash and Windows Batch scripting recently (as part of my ongoing battle to get my HTPC working correctly with MediaPortal).

One problem I kept on coming across was how to pass different variations of the variable you pass to your script, sometimes I wanted the full path to the file, other times I just wanted the filename with the file extension, other times I wanted just the folder the file was located in.

It took a fair bit of googling and experimentation with terms to find the right information, so I have decided to amass it all here to help others (and me).

For Bash Scripting

(taken from linuxgazette)

    Given:

      foo=/tmp/my.dir/filename.tar.gz
    We can use these expressions:
    path = ${foo%/*}
    To get: /tmp/my.dir (like dirname)
    file = ${foo##*/}
    To get: filename.tar.gz (like basename)
    base = ${file%%.*}
    To get: filename
    ext = ${file#*.}
    To get: tar.gz

For Windows Batch Scripting

(taken from imagemagick)

%~1 expands %1 removing any surrounding quotes (“)
%~f1 expands %1 to a fully qualified path name
%~d1 expands %1 to a drive letter only
%~p1 expands %1 to a path only
%~n1 expands %1 to a file name only
%~x1 expands %1 to a file extension only

These two pieces of info can thus be used to pass any variable or variation of that variable to a command in your script.

Using these tools I have been able to get MediaPortal to automatically scan each new recording for adverts using comskip and then transfer the recording, alongside the necessary advert info files to my network hard drive on my server using a batch script. Then the server runs a bash script each morning to scan for new files on the new recordings file, convert them to MKV using Handbrake and add chapter markers and then move the MKV files to my networked videos file. Cool!

Wednesday, July 15th, 2009 Scripts

2 Comments to Bash and Windows batch script file name variable conversion

  1. Would love to hear more about your scripts, especially the HandBrake marker handling. Sounds great.

  2. James on September 1st, 2009
  3. I’ll be adding a post about all the scripts I use for HandBrake and MediaPortal in the next couple of days ;)

  4. prupert on September 6th, 2009

Leave a comment