0

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

you can use bash substring expansion feature.

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

for f in *;do
    mv "$f" "${f%% -*}"
done
  • 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 – Aaron Snowden Dec 12 '16 at 4:11
0

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):

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

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.