linux - [Solved-5 Solutions] Iterate over a list of files with spaces - ubuntu - red hat - debian - linux server - linux pc



Linux - Problem :

If you need to iterate over a list of files. This list is the result of a find command

getlist() {
  for f in $(find . -iname "wiki*")
  do
    echo "File found: $f"
    # do something useful
  done
}
click below button to copy the code. By - Linux tutorial - team

It's fine but if a file has spaces in its name:

$ ls
wiki_bar_baz.txt
wiki bar baz.txt

$ getlist
File found: wiki_bar_baz.txt
File found: wiki
File found: bar
File found: baz.txt
click below button to copy the code. By - Linux tutorial - team

How to avoid the split on spaces?

Linux - Solution 1:

find . -iname "wiki*" | while read f
do
    # ... loop body
done
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 2:

It handles Spaces :

OIFS="$IFS"
IFS=$'\n'
for file in `find . -type f -name "*.csv"`  
do
     echo "file = $file"
     diff "$file" "/some/other/path/$file"
     read line
done
IFS="$OIFS"
click below button to copy the code. By - Linux tutorial - team

It handles wildcards and newlines in file names:

find . -type f -name "*.csv" -print0 | while IFS= read -r -d '' file; do
    echo "file = $file"
    diff "$file" "/some/other/path/$file"
    read line </dev/tty
done
click below button to copy the code. By - Linux tutorial - team

You can use this :

find . -type f -name '*.csv' -exec sh -c '
  file="$0"
  echo "$file"
  diff "$file" "/some/other/path/$file"
  read line </dev/tty
' {} ';'
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 3:

$ mkdir test
$ cd test
$ touch "wikitechy file1"
$ touch "wikitechy file2"
$ touch "wikitechy   file 3"
$ ls
wikitechy  file 3  wikitechy file1     wikitechy file2
$ for file in *; do echo "file: '${file}'"; done
file: 'wikitechy   file 3'
file: 'wikitechy file1'
file: 'wikitechy file2'
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 4:

find . -iname "wiki*" -print0 | xargs -L1 -0 echo "File found:"
click below button to copy the code. By - Linux tutorial - team

Linux - Solution 5:

find . -name "fo*" -print0 | xargs -0 ls -l
click below button to copy the code. By - Linux tutorial - team

Related Searches to - linux - linux tutorial - Iterate over a list of files with spaces