Skip to main content

Sponsors

Using BASH to manipulate all files in a directory - Cont

Posted in

Chris pointed out I can simply do

for i in *; do echo $i ; done

I can recall I struggled on the problem file names broken into parts. I spent much time to solve it. There is nothing much to argue if all other programs except your current script were written correctly. If you forgot to " " your $i, see what will happen below.

xman@sai tmp $ ls -Q
"text1.txt" "text version 2.txt"
xman@sai tmp $ for i in * ; do mv $i $i.txt ; done
mv: target `2.txt.txt' is not a directory
xman@sai tmp $

Now we have two solutions.

Solution I:

for i in *; do mv "$i" "$i.txt" ; done

But do remember to double quote your file names. ;)

Solution II:

export IFS=$'\n'
for i in * ; do mv $i $i.txt ; done

There is nothing wrong if you use "$i".

Currently, I'm not sure what will break what will not if I set IFS=$'\n'. Certainly, if you are using some broken scripts that forgot to " ", with IFS=$'\n', you are still fine. Then, I'll rather locally use IFS=$'\n'. ;) If IFS=$'\n' does break other things, please tell me!

IMHO .. In solution I: each

IMHO ..
In solution I: each element in $i is parsed by space .. all next is irrelevant ..
In solution II: missed "mv" command ? :-)
$i is parsed OK, but in command must be double quoted parameters, for right run mv command .. :-)
sorry for my ugly english, i am only en reader . . :-(

Fixed the missing mv

Fixed the missing mv :) Thanks

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.