1

I have a bunch of files named like this:

File one - some name - 01-05-2020  
File two - some name - 01-07-2020  
File three - some name - 01-15-2020  

What I need is to replace:

  • Single spaces with a hyphen.
  • Hyphens between spaces with an underscore.

My expected result would be:

File-one_some-name_01-05-2020  
File-two_some-name_01-07-2020  
File-three_some-name_01-15-2020 

PD: I'm using Manjaro which is Arch based.

2 Answers 2

3

One solution with mvand sed:

for file in *; do echo mv "$file" "$(echo $file | sed 's/ - /_/g ; s/ /-/g')" ; done

Remove first echo to commit changes.

Tests

$ for file in *; do echo mv "$file" "$(echo $file | sed 's/ - /_/g ; s/ /-/g')" ; done
mv File one - some name - 01-05-2020 File-one_some-name_01-05-2020
mv File three - some name - 01-15-2020 File-three_some-name_01-15-2020
mv File two - some name - 01-07-2020 File-two_some-name_01-07-2020
2
  • Yep, that's what I was looking for, thank you @Paulo Tomé Commented Feb 3, 2020 at 17:26
  • needs to escape the " eg: for file in *; do echo mv \"$file\" "$(echo $file | sed 's/ - /_/g ; s/ /-/g')" ; done Commented Nov 15, 2022 at 14:58
0

Using Larry Wall's "perl rename" (rename on Debian/Ubuntu, prename on RHEL/Centos/Fedora):

rename -n -E 's/ - /_/g' -E 's/ /-/g' {file[s]} 

Remove -n (or replace by -v) for actual execution.

4
  • I'm getting this error: rename: invalid option -- 'E', I forget to specify my distro, I'm using Manjaro which is Arch based, maybe it has something to do with this? Commented Feb 3, 2020 at 17:09
  • There are many commands called rename. man rename should mention Larry Wall in the AUTHOR section at the end. On ArchLinux (and therefore Manjaro) Manjaro it seems to be in the perl-rename package. Commented Feb 3, 2020 at 17:37
  • Indeed it is perl-rename, but it gives me the same error. When I check the available options with --help there is no -E. Commented Feb 3, 2020 at 17:55
  • On mine rename -V says /usr/bin/rename using File::Rename version 0.20. It takes both -e and -E, the difference being that -E adds a ; at the end and as far as I can tell this is required if you have more than one command. Commented Feb 3, 2020 at 18:26

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.