How to iterate over a list of files with spaces in Linux?


In order to iterate over a list of files we will need to make use of the find command that Linux provides us with.

Linux find statement is one of the most widely used statements that allows us to walk a file hierarchy. It is used to mostly find a specific file or directories and we can also append different other Linux statements or flags along with it to enhance or do a complex operation.

Let’s explore an example of a find statement to understand it better.

In the Linux code shown below, I am trying to search for a file inside my Downloads folder, and for that I am making use of the find statement.

find sample.sh

Output

sample.sh

Notice that if the find command is able to locate the file then it will simply print the name of the file, if not then it will not return anything the terminal process will terminate.

Now we know how the find statement works, let’s explore the case where we want to use the find command to print the names of the files that also have spaces in between them.

Consider a directory dir1 where all these files are present.

immukul@192 dir1% ls -ltr
total 5232
-rwxrwxrwx 1 immukul staff 446966 Sep 23 1998 wget-1.5.3.tar.gz
drwxrwxrwx 3 immukul staff 96 Jul 7 17:42 d1
-rwxrwxrwx 1 root staff 106 Jul 8 13:10 sample2.sh
-rwxrwxrwx 1 root    staff 946 Jul 12 18:45 sample.sh
-rwxrwxrwx 1 root    staff 718 Jul 12 18:48 sample1.sh
drwxr-xr-x 2 immukul staff 64 Jul 13 11:36 dr1
drwxr-xr-x 3 immukul staff 96 Jul 13 11:36 dr2
-rw-r--r-- 1 immukul staff 661 Jul 14 09:00 newZip.zip
-rw-r--r-- 1 immukul staff 2201512 Jul 14 09:19 zipContent.zip
drwxrwxrwx 4 immukul staff 128 Jul 14 09:34 d2
-rwxrwxrwx 1 immukul staff 24 Jul 14 15:52 sss.sh
-rw-r--r-- 1 immukul staff 122 Jul 14 16:10 somefile.txt
-rw-r--r-- 1 immukul staff 0 Jul 15 09:44 sample 1.txt

Now we only want to print the names of the files that start with the letter s and also, if we look closely the file name sample 1.txt has space in between its name, and that file should also be printed by the command.

command

The command that will allow us to print the files with spaces is shown below

find . -iname "s*" | while read file
do
   echo $file
done

Output

./sample.sh
./somefile.txt
./sample2.sh
./sample 1.txt
./sss.sh
./sample1.sh

It can be seen clearly that the file that has a space in its name is also printed.

Updated on: 30-Jul-2021

357 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements