Filter a file list against an integer array?How to put the specific files from a directory in an array in bash?How do I aggregate data from many files into one file?How to sum match numbersseparation of files on the basis of their nameFTP script - upload several files with match local folders/ftp foldersUsing awk to process multiple files need to count occurance of variable after pattern. How can I stop array resetting after each file?How to add values to an array which contains a variable in the array name in bash?bash script load an modify array from external filetar “Cannot stat: No such file of directory” when passing array variablesbash command to create array with the 10 most recent images in a dir?

Building a road to escape Earth's gravity by making a pyramid on Antartica

Does any lore text explain why the planes of Acheron, Gehenna, and Carceri are the alignment they are?

What is the right way to float a home lab?

Did Darth Vader wear the same suit for 20+ years?

Can you please explain this joke: "I'm going bananas is what I tell my bananas before I leave the house"?

Prove that a function is indefinitely differentiable

1980s (or earlier) book where people live a long time but they have short memories

Is there any word or phrase for negative bearing?

Chopin: marche funèbre bar 15 impossible place

Credit card offering 0.5 miles for every cent rounded up. Too good to be true?

Opposite of "Squeaky wheel gets the grease"

Linux tr to convert vertical text to horizontal

What happened to all the nuclear material being smuggled after the fall of the USSR?

Riley's, assemble!

Can Green-Flame Blade be cast twice with the Hunter ranger's Horde Breaker ability?

What does War Machine's "Canopy! Canopy!" line mean in "Avengers: Endgame"?

My coworkers think I had a long honeymoon. Actually I was diagnosed with cancer. How do I talk about it?

Bent spoke design wheels — feasible?

Will TSA allow me to carry a Continuous Positive Airway Pressure (CPAP) device?

What is the advantage of carrying a tripod and ND-filters when you could use image stacking instead?

Replace only 2nd, 3rd, nth...character and onwards

How to make thick Asian sauces?

You've spoiled/damaged the card

PhD student with mental health issues and bad performance



Filter a file list against an integer array?


How to put the specific files from a directory in an array in bash?How do I aggregate data from many files into one file?How to sum match numbersseparation of files on the basis of their nameFTP script - upload several files with match local folders/ftp foldersUsing awk to process multiple files need to count occurance of variable after pattern. How can I stop array resetting after each file?How to add values to an array which contains a variable in the array name in bash?bash script load an modify array from external filetar “Cannot stat: No such file of directory” when passing array variablesbash command to create array with the 10 most recent images in a dir?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








2















I have a folder with lots of images named "clip01234-randomlongstring.png", where 01234 is a random five digit number.
I also have an array "clipnumbers" with a list of integers.



Now I want to create a list "files" containing all file names which match the numbers in the "clipnumbers" array. How would I do that?



The resulting output should be something I can process in the same way as my current list (of all files) I create with:
files=($(printf "%sn" *.* | sort -V | tr 'n' ' '))










share|improve this question






























    2















    I have a folder with lots of images named "clip01234-randomlongstring.png", where 01234 is a random five digit number.
    I also have an array "clipnumbers" with a list of integers.



    Now I want to create a list "files" containing all file names which match the numbers in the "clipnumbers" array. How would I do that?



    The resulting output should be something I can process in the same way as my current list (of all files) I create with:
    files=($(printf "%sn" *.* | sort -V | tr 'n' ' '))










    share|improve this question


























      2












      2








      2








      I have a folder with lots of images named "clip01234-randomlongstring.png", where 01234 is a random five digit number.
      I also have an array "clipnumbers" with a list of integers.



      Now I want to create a list "files" containing all file names which match the numbers in the "clipnumbers" array. How would I do that?



      The resulting output should be something I can process in the same way as my current list (of all files) I create with:
      files=($(printf "%sn" *.* | sort -V | tr 'n' ' '))










      share|improve this question
















      I have a folder with lots of images named "clip01234-randomlongstring.png", where 01234 is a random five digit number.
      I also have an array "clipnumbers" with a list of integers.



      Now I want to create a list "files" containing all file names which match the numbers in the "clipnumbers" array. How would I do that?



      The resulting output should be something I can process in the same way as my current list (of all files) I create with:
      files=($(printf "%sn" *.* | sort -V | tr 'n' ' '))







      bash shell-script filenames array






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited May 19 at 0:14









      Jeff Schaller

      46.2k1166150




      46.2k1166150










      asked May 18 at 21:45









      user3647558user3647558

      375




      375




















          5 Answers
          5






          active

          oldest

          votes


















          6














          In a loop:



          shopt -s nullglob

          files=()
          for number in "$clipnumbers[@]"; do
          printf -v pattern 'clip%s-*.png' "$number"
          files+=( $pattern )
          done


          This loops over the numbers and creates a filename globbing pattern for each. The pattern is expanded to add the filenames matching it to the array files. The nullglob shell option makes non-matching patterns expand to nothing (as opposed to remain unexpanded).




          Using find (for recursion into all directories beneath the current directory, and for performing some action on each found file):



          patterns=()
          for number in "$clipnumbers[@]"; do
          printf -v pattern 'clip%s-*.png' "$number"
          patterns+=( -o -name "$pattern" )
          done

          find . -type f ( "$patterns[@]:1" ) -exec action-to-perform-on-files ;


          The :1 removes the initial -o from the list in patterns in the expansion.



          This combines searching for the files with performing some action on them. It would fail if your clipnumbers array contains many thousands of numbers (the argument list would become too long).






          share|improve this answer

























          • oh wow! i did not see the other posts yet but this here certainly works. it's beautiful! thank you so much, all of you!!!

            – user3647558
            May 19 at 1:09


















          3














          Option #1



          Similar to Kusalananda's answer but with array expansion instead of a loop:



          setup



          $ touch clip12710-x.png clip30443-x.png clip57592-x.png clip76672-x.png clip93493-x.png
          $ declare -a array=([0]="30443" [1]="76672" [2]="42424")


          Note that the array contains only two items that are expected to match; there are filenames with clips that are not present and there are clip numbers in array that do not exist as filenames.



          execution



          $ shopt -s nullglob
          $ pfiles=( "$array[@]/#/clip" )
          $ oIFS="$IFS"
          $ IFS=
          $ pfiles=( $pfiles[@]/%/-*.png )
          $ IFS="$oIFS"
          $ declare -p pfiles
          declare -a pfiles=([0]="clip30443-x.png" [1]="clip76672-x.png")


          Note the careful inclusion of double-quotes in the first assignment and the lack of double-quotes in the second assignment. The initial assignment translates the "array" array of numbers into a "pfiles" array of partial filenames by prepending the string clip to each element. The second assignment appends the -*.png wildcard to each element of the array; the lack of quoting in this assignment allows the shell to split each element on $IFS (normally space, tab, and newline), but we've temporarily overridden IFS to be empty. The shell then also "globs" the results, which is what we want here -- for it to expand the "clip...*-png" names into any matching filenames. With the nullglob shell option set, any non-matching wildcards are dropped. The final result is an array in pfiles of files matching clip numbers from your original array.




          Option #2



          (ab)use extended globbing:



          shopt -s extglob nullglob
          declare -a array=([0]="30443" [1]="76672" [2]="42424")
          oIFS="$IFS"
          IFS='|'
          p="$array[*]"
          IFS="$oIFS"
          pfiles=( clip@($p)-*.png )


          This works by setting IFS to the pipe symbol | so that the subsequent assignment to p of array[*] joins the elements of array by pipes (the first character of $IFS at that point). Pipes are the delimiters that bash's extended globbing syntax requires between options in an extended globbing pattern. The last line expands to an array of files that match the extended glob pattern we've constructed:



          • start with clip

          • contain one of the given patterns (clip numbers), now contained in the variable p

          • followed by - then anything

          • and ending in .png

          The nullglob shell option is required in case your clips array does not overlap with any existing filenames.






          share|improve this answer






























            2














            With zsh:



            clipnumbers=(01234 33333)
            files=(clip$^clipnumbers-*.png(N.))


            That expands one glob per clip number. Alternatively, you could turn the array into a glob alternation operator:



            files=(clip($(j:)-*.png(N.))





            share|improve this answer
































              1














              Using GNU grep and printf:



              grep -F $(printf '%sn' "$clipnumbers[@]") clip?????-randomlongstring.png


              Which can be assigned to an array like so:



              files=($(grep -F $(printf '%sn' "$clipnumbers[@]") clip?????-randomlongstring.png))





              share|improve this answer






























                1














                mapfile -t files < <( shopt -s nullglob ; printf "%sn" $(printf "clip%s-*.png " "$clipnumbers[@]" ) )



                • mapfile -t files read lines into files as an array, strip trailing line break.


                • shopt -s nullglob expand non existing pattern to a null string


                • printf "%sn" ... expand patterns, one per line.


                • $(printf "clip%s-*.png " "$arr[@]") ) build patterns.





                share|improve this answer























                  Your Answer








                  StackExchange.ready(function()
                  var channelOptions =
                  tags: "".split(" "),
                  id: "106"
                  ;
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function()
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled)
                  StackExchange.using("snippets", function()
                  createEditor();
                  );

                  else
                  createEditor();

                  );

                  function createEditor()
                  StackExchange.prepareEditor(
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: false,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: null,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader:
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  ,
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  );



                  );













                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function ()
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f519734%2ffilter-a-file-list-against-an-integer-array%23new-answer', 'question_page');

                  );

                  Post as a guest















                  Required, but never shown

























                  5 Answers
                  5






                  active

                  oldest

                  votes








                  5 Answers
                  5






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  6














                  In a loop:



                  shopt -s nullglob

                  files=()
                  for number in "$clipnumbers[@]"; do
                  printf -v pattern 'clip%s-*.png' "$number"
                  files+=( $pattern )
                  done


                  This loops over the numbers and creates a filename globbing pattern for each. The pattern is expanded to add the filenames matching it to the array files. The nullglob shell option makes non-matching patterns expand to nothing (as opposed to remain unexpanded).




                  Using find (for recursion into all directories beneath the current directory, and for performing some action on each found file):



                  patterns=()
                  for number in "$clipnumbers[@]"; do
                  printf -v pattern 'clip%s-*.png' "$number"
                  patterns+=( -o -name "$pattern" )
                  done

                  find . -type f ( "$patterns[@]:1" ) -exec action-to-perform-on-files ;


                  The :1 removes the initial -o from the list in patterns in the expansion.



                  This combines searching for the files with performing some action on them. It would fail if your clipnumbers array contains many thousands of numbers (the argument list would become too long).






                  share|improve this answer

























                  • oh wow! i did not see the other posts yet but this here certainly works. it's beautiful! thank you so much, all of you!!!

                    – user3647558
                    May 19 at 1:09















                  6














                  In a loop:



                  shopt -s nullglob

                  files=()
                  for number in "$clipnumbers[@]"; do
                  printf -v pattern 'clip%s-*.png' "$number"
                  files+=( $pattern )
                  done


                  This loops over the numbers and creates a filename globbing pattern for each. The pattern is expanded to add the filenames matching it to the array files. The nullglob shell option makes non-matching patterns expand to nothing (as opposed to remain unexpanded).




                  Using find (for recursion into all directories beneath the current directory, and for performing some action on each found file):



                  patterns=()
                  for number in "$clipnumbers[@]"; do
                  printf -v pattern 'clip%s-*.png' "$number"
                  patterns+=( -o -name "$pattern" )
                  done

                  find . -type f ( "$patterns[@]:1" ) -exec action-to-perform-on-files ;


                  The :1 removes the initial -o from the list in patterns in the expansion.



                  This combines searching for the files with performing some action on them. It would fail if your clipnumbers array contains many thousands of numbers (the argument list would become too long).






                  share|improve this answer

























                  • oh wow! i did not see the other posts yet but this here certainly works. it's beautiful! thank you so much, all of you!!!

                    – user3647558
                    May 19 at 1:09













                  6












                  6








                  6







                  In a loop:



                  shopt -s nullglob

                  files=()
                  for number in "$clipnumbers[@]"; do
                  printf -v pattern 'clip%s-*.png' "$number"
                  files+=( $pattern )
                  done


                  This loops over the numbers and creates a filename globbing pattern for each. The pattern is expanded to add the filenames matching it to the array files. The nullglob shell option makes non-matching patterns expand to nothing (as opposed to remain unexpanded).




                  Using find (for recursion into all directories beneath the current directory, and for performing some action on each found file):



                  patterns=()
                  for number in "$clipnumbers[@]"; do
                  printf -v pattern 'clip%s-*.png' "$number"
                  patterns+=( -o -name "$pattern" )
                  done

                  find . -type f ( "$patterns[@]:1" ) -exec action-to-perform-on-files ;


                  The :1 removes the initial -o from the list in patterns in the expansion.



                  This combines searching for the files with performing some action on them. It would fail if your clipnumbers array contains many thousands of numbers (the argument list would become too long).






                  share|improve this answer















                  In a loop:



                  shopt -s nullglob

                  files=()
                  for number in "$clipnumbers[@]"; do
                  printf -v pattern 'clip%s-*.png' "$number"
                  files+=( $pattern )
                  done


                  This loops over the numbers and creates a filename globbing pattern for each. The pattern is expanded to add the filenames matching it to the array files. The nullglob shell option makes non-matching patterns expand to nothing (as opposed to remain unexpanded).




                  Using find (for recursion into all directories beneath the current directory, and for performing some action on each found file):



                  patterns=()
                  for number in "$clipnumbers[@]"; do
                  printf -v pattern 'clip%s-*.png' "$number"
                  patterns+=( -o -name "$pattern" )
                  done

                  find . -type f ( "$patterns[@]:1" ) -exec action-to-perform-on-files ;


                  The :1 removes the initial -o from the list in patterns in the expansion.



                  This combines searching for the files with performing some action on them. It would fail if your clipnumbers array contains many thousands of numbers (the argument list would become too long).







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited May 18 at 22:16

























                  answered May 18 at 22:03









                  KusalanandaKusalananda

                  149k18280469




                  149k18280469












                  • oh wow! i did not see the other posts yet but this here certainly works. it's beautiful! thank you so much, all of you!!!

                    – user3647558
                    May 19 at 1:09

















                  • oh wow! i did not see the other posts yet but this here certainly works. it's beautiful! thank you so much, all of you!!!

                    – user3647558
                    May 19 at 1:09
















                  oh wow! i did not see the other posts yet but this here certainly works. it's beautiful! thank you so much, all of you!!!

                  – user3647558
                  May 19 at 1:09





                  oh wow! i did not see the other posts yet but this here certainly works. it's beautiful! thank you so much, all of you!!!

                  – user3647558
                  May 19 at 1:09













                  3














                  Option #1



                  Similar to Kusalananda's answer but with array expansion instead of a loop:



                  setup



                  $ touch clip12710-x.png clip30443-x.png clip57592-x.png clip76672-x.png clip93493-x.png
                  $ declare -a array=([0]="30443" [1]="76672" [2]="42424")


                  Note that the array contains only two items that are expected to match; there are filenames with clips that are not present and there are clip numbers in array that do not exist as filenames.



                  execution



                  $ shopt -s nullglob
                  $ pfiles=( "$array[@]/#/clip" )
                  $ oIFS="$IFS"
                  $ IFS=
                  $ pfiles=( $pfiles[@]/%/-*.png )
                  $ IFS="$oIFS"
                  $ declare -p pfiles
                  declare -a pfiles=([0]="clip30443-x.png" [1]="clip76672-x.png")


                  Note the careful inclusion of double-quotes in the first assignment and the lack of double-quotes in the second assignment. The initial assignment translates the "array" array of numbers into a "pfiles" array of partial filenames by prepending the string clip to each element. The second assignment appends the -*.png wildcard to each element of the array; the lack of quoting in this assignment allows the shell to split each element on $IFS (normally space, tab, and newline), but we've temporarily overridden IFS to be empty. The shell then also "globs" the results, which is what we want here -- for it to expand the "clip...*-png" names into any matching filenames. With the nullglob shell option set, any non-matching wildcards are dropped. The final result is an array in pfiles of files matching clip numbers from your original array.




                  Option #2



                  (ab)use extended globbing:



                  shopt -s extglob nullglob
                  declare -a array=([0]="30443" [1]="76672" [2]="42424")
                  oIFS="$IFS"
                  IFS='|'
                  p="$array[*]"
                  IFS="$oIFS"
                  pfiles=( clip@($p)-*.png )


                  This works by setting IFS to the pipe symbol | so that the subsequent assignment to p of array[*] joins the elements of array by pipes (the first character of $IFS at that point). Pipes are the delimiters that bash's extended globbing syntax requires between options in an extended globbing pattern. The last line expands to an array of files that match the extended glob pattern we've constructed:



                  • start with clip

                  • contain one of the given patterns (clip numbers), now contained in the variable p

                  • followed by - then anything

                  • and ending in .png

                  The nullglob shell option is required in case your clips array does not overlap with any existing filenames.






                  share|improve this answer



























                    3














                    Option #1



                    Similar to Kusalananda's answer but with array expansion instead of a loop:



                    setup



                    $ touch clip12710-x.png clip30443-x.png clip57592-x.png clip76672-x.png clip93493-x.png
                    $ declare -a array=([0]="30443" [1]="76672" [2]="42424")


                    Note that the array contains only two items that are expected to match; there are filenames with clips that are not present and there are clip numbers in array that do not exist as filenames.



                    execution



                    $ shopt -s nullglob
                    $ pfiles=( "$array[@]/#/clip" )
                    $ oIFS="$IFS"
                    $ IFS=
                    $ pfiles=( $pfiles[@]/%/-*.png )
                    $ IFS="$oIFS"
                    $ declare -p pfiles
                    declare -a pfiles=([0]="clip30443-x.png" [1]="clip76672-x.png")


                    Note the careful inclusion of double-quotes in the first assignment and the lack of double-quotes in the second assignment. The initial assignment translates the "array" array of numbers into a "pfiles" array of partial filenames by prepending the string clip to each element. The second assignment appends the -*.png wildcard to each element of the array; the lack of quoting in this assignment allows the shell to split each element on $IFS (normally space, tab, and newline), but we've temporarily overridden IFS to be empty. The shell then also "globs" the results, which is what we want here -- for it to expand the "clip...*-png" names into any matching filenames. With the nullglob shell option set, any non-matching wildcards are dropped. The final result is an array in pfiles of files matching clip numbers from your original array.




                    Option #2



                    (ab)use extended globbing:



                    shopt -s extglob nullglob
                    declare -a array=([0]="30443" [1]="76672" [2]="42424")
                    oIFS="$IFS"
                    IFS='|'
                    p="$array[*]"
                    IFS="$oIFS"
                    pfiles=( clip@($p)-*.png )


                    This works by setting IFS to the pipe symbol | so that the subsequent assignment to p of array[*] joins the elements of array by pipes (the first character of $IFS at that point). Pipes are the delimiters that bash's extended globbing syntax requires between options in an extended globbing pattern. The last line expands to an array of files that match the extended glob pattern we've constructed:



                    • start with clip

                    • contain one of the given patterns (clip numbers), now contained in the variable p

                    • followed by - then anything

                    • and ending in .png

                    The nullglob shell option is required in case your clips array does not overlap with any existing filenames.






                    share|improve this answer

























                      3












                      3








                      3







                      Option #1



                      Similar to Kusalananda's answer but with array expansion instead of a loop:



                      setup



                      $ touch clip12710-x.png clip30443-x.png clip57592-x.png clip76672-x.png clip93493-x.png
                      $ declare -a array=([0]="30443" [1]="76672" [2]="42424")


                      Note that the array contains only two items that are expected to match; there are filenames with clips that are not present and there are clip numbers in array that do not exist as filenames.



                      execution



                      $ shopt -s nullglob
                      $ pfiles=( "$array[@]/#/clip" )
                      $ oIFS="$IFS"
                      $ IFS=
                      $ pfiles=( $pfiles[@]/%/-*.png )
                      $ IFS="$oIFS"
                      $ declare -p pfiles
                      declare -a pfiles=([0]="clip30443-x.png" [1]="clip76672-x.png")


                      Note the careful inclusion of double-quotes in the first assignment and the lack of double-quotes in the second assignment. The initial assignment translates the "array" array of numbers into a "pfiles" array of partial filenames by prepending the string clip to each element. The second assignment appends the -*.png wildcard to each element of the array; the lack of quoting in this assignment allows the shell to split each element on $IFS (normally space, tab, and newline), but we've temporarily overridden IFS to be empty. The shell then also "globs" the results, which is what we want here -- for it to expand the "clip...*-png" names into any matching filenames. With the nullglob shell option set, any non-matching wildcards are dropped. The final result is an array in pfiles of files matching clip numbers from your original array.




                      Option #2



                      (ab)use extended globbing:



                      shopt -s extglob nullglob
                      declare -a array=([0]="30443" [1]="76672" [2]="42424")
                      oIFS="$IFS"
                      IFS='|'
                      p="$array[*]"
                      IFS="$oIFS"
                      pfiles=( clip@($p)-*.png )


                      This works by setting IFS to the pipe symbol | so that the subsequent assignment to p of array[*] joins the elements of array by pipes (the first character of $IFS at that point). Pipes are the delimiters that bash's extended globbing syntax requires between options in an extended globbing pattern. The last line expands to an array of files that match the extended glob pattern we've constructed:



                      • start with clip

                      • contain one of the given patterns (clip numbers), now contained in the variable p

                      • followed by - then anything

                      • and ending in .png

                      The nullglob shell option is required in case your clips array does not overlap with any existing filenames.






                      share|improve this answer













                      Option #1



                      Similar to Kusalananda's answer but with array expansion instead of a loop:



                      setup



                      $ touch clip12710-x.png clip30443-x.png clip57592-x.png clip76672-x.png clip93493-x.png
                      $ declare -a array=([0]="30443" [1]="76672" [2]="42424")


                      Note that the array contains only two items that are expected to match; there are filenames with clips that are not present and there are clip numbers in array that do not exist as filenames.



                      execution



                      $ shopt -s nullglob
                      $ pfiles=( "$array[@]/#/clip" )
                      $ oIFS="$IFS"
                      $ IFS=
                      $ pfiles=( $pfiles[@]/%/-*.png )
                      $ IFS="$oIFS"
                      $ declare -p pfiles
                      declare -a pfiles=([0]="clip30443-x.png" [1]="clip76672-x.png")


                      Note the careful inclusion of double-quotes in the first assignment and the lack of double-quotes in the second assignment. The initial assignment translates the "array" array of numbers into a "pfiles" array of partial filenames by prepending the string clip to each element. The second assignment appends the -*.png wildcard to each element of the array; the lack of quoting in this assignment allows the shell to split each element on $IFS (normally space, tab, and newline), but we've temporarily overridden IFS to be empty. The shell then also "globs" the results, which is what we want here -- for it to expand the "clip...*-png" names into any matching filenames. With the nullglob shell option set, any non-matching wildcards are dropped. The final result is an array in pfiles of files matching clip numbers from your original array.




                      Option #2



                      (ab)use extended globbing:



                      shopt -s extglob nullglob
                      declare -a array=([0]="30443" [1]="76672" [2]="42424")
                      oIFS="$IFS"
                      IFS='|'
                      p="$array[*]"
                      IFS="$oIFS"
                      pfiles=( clip@($p)-*.png )


                      This works by setting IFS to the pipe symbol | so that the subsequent assignment to p of array[*] joins the elements of array by pipes (the first character of $IFS at that point). Pipes are the delimiters that bash's extended globbing syntax requires between options in an extended globbing pattern. The last line expands to an array of files that match the extended glob pattern we've constructed:



                      • start with clip

                      • contain one of the given patterns (clip numbers), now contained in the variable p

                      • followed by - then anything

                      • and ending in .png

                      The nullglob shell option is required in case your clips array does not overlap with any existing filenames.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered May 19 at 0:36









                      Jeff SchallerJeff Schaller

                      46.2k1166150




                      46.2k1166150





















                          2














                          With zsh:



                          clipnumbers=(01234 33333)
                          files=(clip$^clipnumbers-*.png(N.))


                          That expands one glob per clip number. Alternatively, you could turn the array into a glob alternation operator:



                          files=(clip($(j:)-*.png(N.))





                          share|improve this answer





























                            2














                            With zsh:



                            clipnumbers=(01234 33333)
                            files=(clip$^clipnumbers-*.png(N.))


                            That expands one glob per clip number. Alternatively, you could turn the array into a glob alternation operator:



                            files=(clip($(j:)-*.png(N.))





                            share|improve this answer



























                              2












                              2








                              2







                              With zsh:



                              clipnumbers=(01234 33333)
                              files=(clip$^clipnumbers-*.png(N.))


                              That expands one glob per clip number. Alternatively, you could turn the array into a glob alternation operator:



                              files=(clip($(j:)-*.png(N.))





                              share|improve this answer















                              With zsh:



                              clipnumbers=(01234 33333)
                              files=(clip$^clipnumbers-*.png(N.))


                              That expands one glob per clip number. Alternatively, you could turn the array into a glob alternation operator:



                              files=(clip($(j:)-*.png(N.))






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited May 19 at 6:31

























                              answered May 19 at 6:26









                              Stéphane ChazelasStéphane Chazelas

                              320k57608979




                              320k57608979





















                                  1














                                  Using GNU grep and printf:



                                  grep -F $(printf '%sn' "$clipnumbers[@]") clip?????-randomlongstring.png


                                  Which can be assigned to an array like so:



                                  files=($(grep -F $(printf '%sn' "$clipnumbers[@]") clip?????-randomlongstring.png))





                                  share|improve this answer



























                                    1














                                    Using GNU grep and printf:



                                    grep -F $(printf '%sn' "$clipnumbers[@]") clip?????-randomlongstring.png


                                    Which can be assigned to an array like so:



                                    files=($(grep -F $(printf '%sn' "$clipnumbers[@]") clip?????-randomlongstring.png))





                                    share|improve this answer

























                                      1












                                      1








                                      1







                                      Using GNU grep and printf:



                                      grep -F $(printf '%sn' "$clipnumbers[@]") clip?????-randomlongstring.png


                                      Which can be assigned to an array like so:



                                      files=($(grep -F $(printf '%sn' "$clipnumbers[@]") clip?????-randomlongstring.png))





                                      share|improve this answer













                                      Using GNU grep and printf:



                                      grep -F $(printf '%sn' "$clipnumbers[@]") clip?????-randomlongstring.png


                                      Which can be assigned to an array like so:



                                      files=($(grep -F $(printf '%sn' "$clipnumbers[@]") clip?????-randomlongstring.png))






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered May 19 at 0:15









                                      agcagc

                                      5,03311338




                                      5,03311338





















                                          1














                                          mapfile -t files < <( shopt -s nullglob ; printf "%sn" $(printf "clip%s-*.png " "$clipnumbers[@]" ) )



                                          • mapfile -t files read lines into files as an array, strip trailing line break.


                                          • shopt -s nullglob expand non existing pattern to a null string


                                          • printf "%sn" ... expand patterns, one per line.


                                          • $(printf "clip%s-*.png " "$arr[@]") ) build patterns.





                                          share|improve this answer



























                                            1














                                            mapfile -t files < <( shopt -s nullglob ; printf "%sn" $(printf "clip%s-*.png " "$clipnumbers[@]" ) )



                                            • mapfile -t files read lines into files as an array, strip trailing line break.


                                            • shopt -s nullglob expand non existing pattern to a null string


                                            • printf "%sn" ... expand patterns, one per line.


                                            • $(printf "clip%s-*.png " "$arr[@]") ) build patterns.





                                            share|improve this answer

























                                              1












                                              1








                                              1







                                              mapfile -t files < <( shopt -s nullglob ; printf "%sn" $(printf "clip%s-*.png " "$clipnumbers[@]" ) )



                                              • mapfile -t files read lines into files as an array, strip trailing line break.


                                              • shopt -s nullglob expand non existing pattern to a null string


                                              • printf "%sn" ... expand patterns, one per line.


                                              • $(printf "clip%s-*.png " "$arr[@]") ) build patterns.





                                              share|improve this answer













                                              mapfile -t files < <( shopt -s nullglob ; printf "%sn" $(printf "clip%s-*.png " "$clipnumbers[@]" ) )



                                              • mapfile -t files read lines into files as an array, strip trailing line break.


                                              • shopt -s nullglob expand non existing pattern to a null string


                                              • printf "%sn" ... expand patterns, one per line.


                                              • $(printf "clip%s-*.png " "$arr[@]") ) build patterns.






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered May 19 at 1:32









                                              dedowsdidedowsdi

                                              70416




                                              70416



























                                                  draft saved

                                                  draft discarded
















































                                                  Thanks for contributing an answer to Unix & Linux Stack Exchange!


                                                  • Please be sure to answer the question. Provide details and share your research!

                                                  But avoid


                                                  • Asking for help, clarification, or responding to other answers.

                                                  • Making statements based on opinion; back them up with references or personal experience.

                                                  To learn more, see our tips on writing great answers.




                                                  draft saved


                                                  draft discarded














                                                  StackExchange.ready(
                                                  function ()
                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f519734%2ffilter-a-file-list-against-an-integer-array%23new-answer', 'question_page');

                                                  );

                                                  Post as a guest















                                                  Required, but never shown





















































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown

































                                                  Required, but never shown














                                                  Required, but never shown












                                                  Required, but never shown







                                                  Required, but never shown







                                                  Popular posts from this blog

                                                  Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

                                                  Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

                                                  Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020