5

I have several files that are named like this: file - name.txt

How do I remove the " - " using a bash script in UNIX from all the files?

3 Answers 3

3

If I understand correctly, try rename ' - ' '' *

Sign up to request clarification or add additional context in comments.

1 Comment

It exists in some distros and there are at least two inconsistent implementations. It is not a POSIX tool.
2

Use parameter expansion to remove the part of the string you want to be rid of. Make sure to use double-quotes to prevent mv from misinterpreting input.

for i in ./*' - '*; do
    mv "$i" "${i// - }"
done

2 Comments

OK thanks! That worked! Also, using that same method, how would I be able to store the part of the filename before the " - " in a separate string?
@Generalkidd separateString="${i%% - *}"
1

Sed it up!

# Iterate each file in the current directory.
for i in *; do
  # Move the file to the new filename, replacing ' - ' with '_'
  mv "$i" `echo $i | sed 's/ - /_/g'`
done

1 Comment

Doh. I am used to zsh - fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.