← Back to context

Comment by mtift

4 years ago

Totally inefficient. But for me it's readable and practical. This is mostly just a convenience function for me to help store files in a format I like rather than something I need optimized. If it ever started to feel slow, sure I could optimize. But for now, when I still occasionally download a file that has some weird character and I just prefer to add another line to my function.

Without changing the design too much, you could rearrange it like so to avoid renaming multiple times and still have the option to just "add another line":

  # Rename all files in a directory
  rn() {
    rename \
      -e "s/ /-/g" \
      -e "s/_/-/g" \
      -e "s/–/-/g" \
      -e "s/://g" \
      -e "s/\(//g" \
      -e "s/\)//g" \
      -e "s/\[//g" \
      -e "s/\]//g" \
      -e 's/"//g' \
      -e "s/'//g" \
      -e "s/,//g" \
      -e "y/A-Z/a-z/" \
      -e "s/---/--/g" \
      -e "s/-‎--/--/g" \
      *
  }

Though I would at least take advantage of character classes to reduce the number of substitutions:

  # Rename all files in a directory
  rn() {
    rename \
      -e 's/[ _—]/-/g' \
      -e 's/[:\(\)\[\]",]//g' \
      -e "s/'//g" \
      -e 'y/A-Z/a-z/' \
      -e 's/--+/--/g' \
      *
  }

(I'm using the `rename` command provided by the `rename` Debian package, a.k.a `file-rename`. The options may vary if you're using a different version.)