-   Linux - Newbie (
-   -   understand IFS change for looping files with spaces (

vincix 01-31-2017 03:15 AM

understand IFS change for looping files with spaces
The other day I was trying to loop some files that contained spaces. I was trying to delete the same string that appeared at the beginning of several files using substring removal.
Suppose the filename is "First - Second - file.txt" and I'd like to remove "First - Second - " so that only "file.txt" remains.
So I tried:

for i in First*; do mv $i ${i##* }; done.
But it didn't work and then someone told me that I needed to change the IFS. Which I did, following these instructions:

And it worked just fine.
The site suggests using IFS=$(echo -en "\n\b")

Could anyone explain to me exactly what is going on? How does bash process the loop and why does one need a backspace after a newline? I really don't understand the mechanism, even if it would seem rather basic.

allend 01-31-2017 05:41 AM

You need to quote the variables,

for i in First*; do mv "$i" "${i##* }"; done
otherwise the command expands to

mv First - Second - file.txt file.txt
instead of

mv "First - Second - file.txt" "file.txt"
as you want.

grail 01-31-2017 07:36 AM

Above is solution, but if I may, until you are 100%, ALWAYS quote variables in bash.

vincix 01-31-2017 10:18 AM

I suppose that's much easier. Thanks :)

grail 01-31-2017 10:56 AM

Please mark as SOLVED once you have a solution.

All times are GMT -5. The time now is 08:34 PM.