You are not logged in.

#1 2006-10-14 14:09:53

drakosha
Member
Registered: 2006-01-03
Posts: 253
Website

work with files with spaces in bash [SOLVED]

I want to rename some files with spaces in names. For example i have 2 files i need to remove first several chars from their names.
   

/tmp/tst>ls -l
    total 0
    -rw-r–r– 1 noone users 0 2006-10-14 10:54 this is file 1.txt
    -rw-r–r– 1 noone users 0 2006-10-14 10:54 this is file 2.txt

I'd like to have the following result:

    /tmp/tst>ls -l
    total 0
    -rw-r–r– 1 noone users 0 2006-10-14 10:54 is file 1.txt
    -rw-r–r– 1 noone users 0 2006-10-14 10:54 is file 2.txt

Well, the obvious way would be:

for f in `ls`
do
    mv $f `echo $f | cut -b 5-`
done

But it doesn't work, here's the problem, file names have spaces:

for f in `ls`; do echo mv $f `echo $f | cut -b 5-`; done
    mv this this
    mv is
    mv file
    mv 1.txt t
    mv this this
    mv is
    mv file
    mv 2.txt t
    mv

After some googling, i got the following way of treating file names with spaces:

find . -type f | while read file; do echo mv '$file' '`echo $file | cut -b 8-`'; done;
mv './this is file 1.txt' 'is file 1.txt'
mv './this is file 2.txt' 'is file 2.txt'

Well, it looks to be working, let's remove the echo and see what happens:
   

find . -type f | while read file; do mv '$file' '`echo $file | cut -b 8-`'; done;
mv: target `1.txt'' is not a directory
mv: target `2.txt'' is not a directory

Here i gave up and i just did copy-paste of the 'echo' results before into the shell.
What should i do to make it work? Bash experts, HELP!

Offline

#2 2006-10-14 14:29:38

zen_guerrilla
Member
From: Greece
Registered: 2002-12-22
Posts: 259

Re: work with files with spaces in bash [SOLVED]

Put the filenames in " ". ie:

this line:

mv $f `echo $f | cut -b 5-`

becomes

mv "$f" "`echo $f | cut -b 5-`"

Offline

#3 2006-10-14 15:20:40

drakosha
Member
Registered: 2006-01-03
Posts: 253
Website

Re: work with files with spaces in bash [SOLVED]

Wow! thanks a lot!!!

Offline

#4 2006-10-14 16:45:14

zen_guerrilla
Member
From: Greece
Registered: 2002-12-22
Posts: 259

Re: work with files with spaces in bash [SOLVED]

N.P.

btw. sed is really useful for mass renaming files. I use it all the time to manage my music collection. For example if you want to remove the word 'zen_guerrilla' from a bunch of files run the following:

for file in *; do mv "$file" "`echo $file | sed -e 's:zen_guerrilla::'`"; done

Offline

#5 2006-10-16 14:49:04

phrakture
Arch Overlord
From: behind you
Registered: 2003-10-29
Posts: 7,879
Website

Re: work with files with spaces in bash [SOLVED]

Important bash tip - quote everything 95% of the time

Offline

Board footer

Powered by FluxBB