I have directories:

  • Foo
  • Fee

but I also have some directories with names like:

  • Ipsum - Lorem
  • Dolor - Sit

If the directory does not contain a hyphen is should be ignored If the directory does contain a hyphen: Mkdir Ipsum; mv Ipsum\ -\ * Ipsum

Is this possible?

Edit for clarification: If there is a directory with a hyphen I want to create a new directory name based on the part pre-hyphen and then move ALL directories that include the pre-hyphen part into that new directory.

2 Answers 2


you can use bash substring expansion feature.

${parameter%%word} Remove matching suffix pattern.

for f in *;do
    mv "$f" "${f%% -*}"
  • Your response came before my clarification but gave me the missing puzzle pieces I needed to fix my problem. for f in *;do mkdir "${f%% -*}" mv "${f%% -*}"\ -* "${f%% -*}"; done Dec 12, 2016 at 4:11

Yes, it is possible. Put code like this in a file, say fix-dashes.sh (I am on Mac OS, but this should work on other Unices):

IFS=$(echo -en "\n\b")
trap 'IFS=$SAVEIFS' 0
for i in $@
  echo Processing $i
  case $i in
      echo "'$i' has a dash"
      destname=$(echo "$i" | sed 's/ -.*//')
      echo mv "$i" $destname
      mv "$i" $destname

Then bash fix-dash.sh */ will rename the directories as you specified. The slash is important so that you only get directory names, otherwise regular files with dashes will be affected.

`IFS contains the delimiters for the words and since your file names have spaces you need to adjust.

I like using the limited Regular expression mechanism of case because it mimics the REs used by bash on the command line. In this case, only names containing dashes will cause the rename to be executed.

The sed command does the transformation, in this case, substituting everything after the first with the null string.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .