W
W
wolverine7772020-06-01 11:28:14
linux
wolverine777, 2020-06-01 11:28:14

How to loop through directories with spaces?

Hello, let's say I need to collect all the files with the .txt extension from anywhere on my computer.

I first installed the extremely handy locate

sudo apt-get install locate
and then the following script

#!/bin/bash

for book in $(locate .txt)
do
  echo "cp ${book} /mnt/e/BOOK"
done


is executed only when there are no spaces in the source folder\file - and thus the found file is safely copied to the specified folder.

If there is a gap, the path breaks and everything is bad.

Surely there is some simple solution?

Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Victor Taran, 2020-06-01
@shambler81

find . -regex ".*\.\(jpg\|jpeg\|gif\|png\|JPG\|JPEG\|GIF\|PNG\)" -print0 | xargs -0 cp --parents --target-directory ./tmp/backup

with the preservation of the structure
find . -regex ".*\.\(jpg\|jpeg\|gif\|png\|JPG\|JPEG\|GIF\|PNG\)" -print0 | xargs -0 cp ./tmp/backup

without

J
jcmvbkbc, 2020-06-01
@jcmvbkbc

Surely there is some simple solution?

The classic is to separate the names with zeros:
locate -0 '.txt' | xargs -0 -I\{} echo 'cp "{}" /mnt/e/BOOK'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question