Home > Net >  Replace multiple underscores in filename using bash script
Replace multiple underscores in filename using bash script

Time:12-01

Doing some reading here and here I found this solution to replace two underscores in filenames with only one using bash:

for file in *; do
  f=${file//__/_}
  echo $f
done;

However how do I most easily expand this expression to replace an arbitrary number of underscores with only one?

CodePudding user response:

Typically, it's going to be faster to just put your original code in a loop than to do anything else.

for file in *; do
  f=$file
  while [[ $f = *__* ]]; do
    f=${f//__/_}
  done
  echo "$f"
done

Even better, if you're on a modern shell release, you can enable extended globs, which provide regex-like functionality:

shopt -s extglob
for file in *; do
  f=${file// (_)/_}
  echo "$f"
done

CodePudding user response:

You could use a simple regex using sed

for file in *; do
  f=$(echo "$file" | sed -e 's/_\ /_/')
  echo "$f"
done;

This regex matches one or more underscores (_\ ) and substitutes them with only one (_)

CodePudding user response:

GNU tr has --squeeze-repeats:

$ echo foo_______bar | tr --squeeze-repeats _
foo_bar

If you're using BSD tr you can use -s instead:

$ echo foo_______bar | tr -s _
foo_bar
  • Related