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)


    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!

2 thoughts on “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.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.