Jump to content

Replace spaces with dashes in file name

Recommended Posts

I have a simple bash file to create a new markdown file named with the current date as well as the file name I input via {query} which works correctly...


touch ~/folder/_posts/$( date '+%Y-%m-%d-' )"$file"

Is there an easy way to add code to replace spaces in the file name with dashes? Obviously, the date is formatted correctly. It would be so much easier to just type "this is the name of my file" versus "this-is-the-name-of-my-file".


Also, how would I then have the file opened in my editor of choice? Usually the following works but for some reason is not. Probably the way I'm referencing $file.

open -a "Byword" "$file"



Link to comment

Replace spaces with dashes in the shell (sh, bash, zsh, etc.):

echo "Lorem ipsum dolor sit amet" | tr " " "-"
# --> "Lorem-ipsum-dolor-sit-amet"

If you only want the date to be dash-free, do:

$( date '+%Y %m %d ' )

The open command doesn't seem to like "\ " combinations. Try telling Alfred to leave spaces unescaped:


Edited by Tyler Eich
Link to comment

Still learning my way around Terminal so I know I'm missing something.


I've tried adding

| tr " " "-"


touch ~/folder/_posts/$( date '+%Y-%m-%d-' )"$file"

which clearly is not correct. I'm not sure how the echo command would be used here.


To have the file opened in my editor, I just had to point it to the path.

open -a "Byword" ~/folder/_posts/"$file"
Edited by jarhead
Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Create New...