-2

How can I move few files that contain spaces to another directory using a bash script?

file name: "Sublime Text 3.x"

my code is :

for file in $(ls -t | tail -n +1)
do 
mv $file /tmp/test
done

Output shows as:

mv: cannot stat ‘Sublime’: No such file or directory
mv: cannot stat ‘Text’: No such file or directory
mv: cannot stat ‘3.x’: No such file or directory
techraf
  • 4,243
  • 8
  • 29
  • 44
Anas KK
  • 5
  • 1

2 Answers2

1

You can achieve this by

ls -t | grep ' ' | while read file; do mv "$file" /tmp/test; done

Hope this helps, you can ask the queries if you have any!

Anirudh Malhotra
  • 1,290
  • 8
  • 11
0

You'll need to put quotes around the string when you use it for the ls and the move command:

for file in "$(ls -t | tail -n +1)"
do
  mv "$file" /tmp/test
done

Try that.

Longer explanation:

When you look closely at the output of your example, you see that the interpreter tries three times:

first it tries to move the file 'Sublime'

Then it tries to move the file 'Text'

and lastly it tries to move the file '3.x'

The hint you may pick up is that they are separated by a space. You are able to move three files in one go with the mv command, but only if those files exist.

so:

mv file1.txt file2.txt file3.txt /some/destination/dir

..can be a valid command to move three files.

To prevent the interpreter to look for individual files (separated by a space) you can tell it to take the full filename (including spaces) when you surround the variable with spaces.

Good question!

captcha
  • 578
  • 5
  • 16
  • Nothing has been changed when I updated script to: mv "$file" /tmp/test – Anas KK Nov 02 '16 at 05:12
  • Ah.. also add quotes around the ls command.. See my updated answer. – captcha Nov 02 '16 at 05:16
  • Now error msg shows as: "mv: cannot stat ‘Plazid virtual tour.zip\nLeave Request Format.docx\nSublime Text 3\nSublime Text 3.x Serial Only\nSunn Raha Hai.lrc’: No such file or directory" – Anas KK Nov 02 '16 at 05:37