You are not logged in.

#1 2020-07-31 18:46:15

Skaper
Member
Registered: 2020-03-02
Posts: 14

The "rename" command does not replace the space in a file name

Hi,

I am trying to write a script that will substitute spaces in file names into underscores. mv command does not work, as it expects a directory as the last argument for some reason. I read about rename command and so I tried the following;

 rename 's/\ /_/g' ${1}

This produces an error stating it does not have enough arguments for some reason. Upon reading the man page I found out that the correct way of writing the command is the following (which works but not completely);

rename \  _ ${1} # There is a space after backslash.

This works but the problem is it only replaces the first ever blank space in the name of the file. Searching the internet, I only found the first mentioned use of the command.

How do I make it so that the command replaces all of the spaces in the file name?


I like to do things a certain way, even if there's a simpler solution available. (No one will hire me, I know.)

Offline

#2 2020-07-31 19:06:52

eschwartz
Trusted User/Bug Wrangler
Registered: 2014-08-08
Posts: 3,534

Re: The "rename" command does not replace the space in a file name

There are two rename commands. The good one is in the perl-rename package and, appropriately, is `perl-rename 's/\ /_/g' ${1}`, the mediocre one comes from util-linux and is installed by default.

Some linux distributions call it "prename" or "file-rename", and/or offer an option to choose between the two for the /usr/bin/rename file.


Managing AUR repos The Right Way -- aurpublish (now a standalone tool)

Offline

#3 2020-07-31 19:22:12

jasonwryan
Anarchist
From: .nz
Registered: 2009-05-09
Posts: 29,025
Website

Re: The "rename" command does not replace the space in a file name

for target in *, do mv "$target" "${target// /_}"; done

#edit thanks seth smile

Last edited by jasonwryan (2020-07-31 20:38:35)


Arch + dwm   •   Mercurial repos  •   Surfraw

Registered Linux User #482438

Offline

#4 2020-08-01 05:34:05

Skaper
Member
Registered: 2020-03-02
Posts: 14

Re: The "rename" command does not replace the space in a file name

jasonwryan wrote:
for target in *, do mv "$target" "${target// /_}"; done

Thank you. That worked.


I like to do things a certain way, even if there's a simpler solution available. (No one will hire me, I know.)

Offline

Board footer

Powered by FluxBB