Rephrasing your question:
I have filenames and directory names (some of which are duplicates
and some others are nonexistent) stored as elements in an
array(original
) ... In bash
, how can I test and process the
elements in the original
array into a new array refined
excluding
duplicate and nonexistent filenames/directory names ... And at the
same time creating two new arrays files
(containing only refined
filenames) and directories
(containing only refined directory
names)?
Issue reproduction:
# Create some test files
$ touch file{1..3}
# Create some test directories
$ mkdir dir{1..3}
# List current working directory contents
$ printf '%s\n' *
dir1
dir2
dir3
file1
file2
file3
# Add contents to an array
$ for i in *
do
original+=( "$i" )
done
# Add contents to the same array again to generate duplicates
$ for i in *
do
original+=( "$i" )
done
# Add some invalid entries
$ original+=( "file4" "dir4" "file5" "dir5" )
# Print the array
$ printf '%s\n' "${original[@]}"
dir1
dir2
dir3
file1
file2
file3
dir1
dir2
dir3
file1
file2
file3
file4
dir4
file5
dir5
Possible solution:
# Test, refine and classify array items
$ for i in "${original[@]}"
do
if [[ ! "${refined[*]}" =~ "$i" ]]
then
[ -f "$i" ] && refined+=( "$i" ) && files+=( "$i" )
[ -d "$i" ] && refined+=( "$i" ) && directories+=( "$i" )
fi
done
# Print the "refined" array
$ printf '%s\n' "${refined[@]}"
dir1
dir2
dir3
file1
file2
file3
# Print the "files" array
$ printf '%s\n' "${files[@]}"
file1
file2
file3
# Print the "directories" array
$ printf '%s\n' "${directories[@]}"
dir1
dir2
dir3