0

We need to find files in a directory with name containing a specific string and add them in a list.

Suppose we create list containing files names in a specific directory containing string ABC.

Tried this one:

file_list=()
str="ABC"
while IFS= read -d $'\0' -r file ; do
file_list=("${file_list[@]}" "$file")
done < <(find . -name "*$str*" -print0)
echo "Files getting appended: ${file_list[@]}"

If the directory contain files:

ABC.txt, ABCD.txt, XYZ.txt, WXYZ.txt

Then expected output of the above snippet should be:

Files getting appended: ABC.txt ABCD.txt

Getting error message in AIX:

find: 0652-017 -print0 is not a valid option.

Got a related post which works for Linux but got no luck in AIX.

Any help will really be appriciated!

RandomCoder
  • 79
  • 1
  • 7

1 Answers1

1

Indeed, AIX!find doesn't support -print0. Try something like this:

#!/usr/local/bin/bash

file_list=()

touch xABCy
touch 'x ABC y'

str="ABC"

while IFS='\n' read -r file ; do
    file_list+=("$file")
done < <(find . -name "*$str*")

for i in "${file_list[@]}"; do
    printf '\"%s\"\n' "$i"
done

result:

"./x ABC y"
"./xABCy"
Lorinczy Zsigmond
  • 1,749
  • 1
  • 14
  • 21
  • Collecting the results into a hash so you can loop over the hash is kind of funny. Just print in the first loop and don't collect the values. – tripleee Nov 27 '18 at 09:01
  • Sure, the second loop is only there for debugging: it proves that filenames-with-spaces are processed correctly. The actual script is supposed to do some actual work with `file_list` – Lorinczy Zsigmond Nov 27 '18 at 09:48
  • I'm pointing this out because needlessly collecting things into variables is a common anti-pattern. If you don't need random access (go back, see how many you collected, compare the file names m*n, skip two, etc) you don't want or need an array here. – tripleee Nov 27 '18 at 10:17