bash command to create array with the 10 most recent images in a dir? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Community Moderator Election Results Why I closed the “Why is Kali so hard” questionFinding all “Non-Binary” filesFinding all kinds of extensions referenced in a html fileHow to do more than one substring replace at once in bash?Create array in bash with variables as array nameDynamically create array in bash with variables as array namebash array with variable in the nameHow can I find files with a long first line?find modified files recursively and copy with directory preserving directory structureCreate new array with unique values from existing arrayHow to rsync chronologically starting with the most recent files

Letter Boxed validator

Why does Python start at index 1 when iterating an array backwards?

What are the pros and cons of Aerospike nosecones?

Right-skewed distribution with mean equals to mode?

How widely used is the term Treppenwitz? Is it something that most Germans know?

Single word antonym of "flightless"

How to draw this diagram using TikZ package?

What makes black pepper strong or mild?

Is 1 ppb equal to 1 μg/kg?

How discoverable are IPv6 addresses and AAAA names by potential attackers?

How do I keep my slimes from escaping their pens?

IndentationError when pasting code in Python 3 interpreter mode

Can inflation occur in a positive-sum game currency system such as the Stack Exchange reputation system?

Why don't the Weasley twins use magic outside of school if the Trace can only find the location of spells cast?

When is phishing education going too far?

When to stop saving and start investing?

How can I make names more distinctive without making them longer?

Is there a concise way to say "all of the X, one of each"?

How was the dust limit of 546 satoshis was chosen? Why not 550 satoshis?

Why is black pepper both grey and black?

Is it true to say that an hosting provider's DNS server is what links the entire hosting environment to ICANN?

What LEGO pieces have "real-world" functionality?

Is there a way in Ruby to make just any one out of many keyword arguments required?

Why is "Consequences inflicted." not a sentence?



bash command to create array with the 10 most recent images in a dir?



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
2019 Community Moderator Election Results
Why I closed the “Why is Kali so hard” questionFinding all “Non-Binary” filesFinding all kinds of extensions referenced in a html fileHow to do more than one substring replace at once in bash?Create array in bash with variables as array nameDynamically create array in bash with variables as array namebash array with variable in the nameHow can I find files with a long first line?find modified files recursively and copy with directory preserving directory structureCreate new array with unique values from existing arrayHow to rsync chronologically starting with the most recent files



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








2















I'm writing a bash script and I need to create an array with the 10 most recent image files (from new to old) in the current dir.



I consider "image files" to be files with certain extensions, like .jpg or .png. I only require a few specific image types to be supported, I can also express this in one regex like ".(jpg|png)$".



My problem is, if I try to do this with e.g. $list=(ls -1t *.jpg *.png | head -10) the resulting list of files somehow becomes one element, instead of each filename being a separate element in my array.



If I try to use $list=(find -E . -iregex ".*(jpg|png)" -maxdepth 1 -type f | head -10), I'm not sure how to sort the list on date/time and keep only the filenames. Also find seems to put ./ in front of every file but I can get rid of that with sed. And also with find I still have the problem of my entire list becoming one entry in the $list array.










share|improve this question






















  • Is bash a hard requirement, or is a zsh solution acceptable?

    – Jeff Schaller
    6 hours ago

















2















I'm writing a bash script and I need to create an array with the 10 most recent image files (from new to old) in the current dir.



I consider "image files" to be files with certain extensions, like .jpg or .png. I only require a few specific image types to be supported, I can also express this in one regex like ".(jpg|png)$".



My problem is, if I try to do this with e.g. $list=(ls -1t *.jpg *.png | head -10) the resulting list of files somehow becomes one element, instead of each filename being a separate element in my array.



If I try to use $list=(find -E . -iregex ".*(jpg|png)" -maxdepth 1 -type f | head -10), I'm not sure how to sort the list on date/time and keep only the filenames. Also find seems to put ./ in front of every file but I can get rid of that with sed. And also with find I still have the problem of my entire list becoming one entry in the $list array.










share|improve this question






















  • Is bash a hard requirement, or is a zsh solution acceptable?

    – Jeff Schaller
    6 hours ago













2












2








2


2






I'm writing a bash script and I need to create an array with the 10 most recent image files (from new to old) in the current dir.



I consider "image files" to be files with certain extensions, like .jpg or .png. I only require a few specific image types to be supported, I can also express this in one regex like ".(jpg|png)$".



My problem is, if I try to do this with e.g. $list=(ls -1t *.jpg *.png | head -10) the resulting list of files somehow becomes one element, instead of each filename being a separate element in my array.



If I try to use $list=(find -E . -iregex ".*(jpg|png)" -maxdepth 1 -type f | head -10), I'm not sure how to sort the list on date/time and keep only the filenames. Also find seems to put ./ in front of every file but I can get rid of that with sed. And also with find I still have the problem of my entire list becoming one entry in the $list array.










share|improve this question














I'm writing a bash script and I need to create an array with the 10 most recent image files (from new to old) in the current dir.



I consider "image files" to be files with certain extensions, like .jpg or .png. I only require a few specific image types to be supported, I can also express this in one regex like ".(jpg|png)$".



My problem is, if I try to do this with e.g. $list=(ls -1t *.jpg *.png | head -10) the resulting list of files somehow becomes one element, instead of each filename being a separate element in my array.



If I try to use $list=(find -E . -iregex ".*(jpg|png)" -maxdepth 1 -type f | head -10), I'm not sure how to sort the list on date/time and keep only the filenames. Also find seems to put ./ in front of every file but I can get rid of that with sed. And also with find I still have the problem of my entire list becoming one entry in the $list array.







bash find sort array file-search






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked 8 hours ago









RocketNutsRocketNuts

133114




133114












  • Is bash a hard requirement, or is a zsh solution acceptable?

    – Jeff Schaller
    6 hours ago

















  • Is bash a hard requirement, or is a zsh solution acceptable?

    – Jeff Schaller
    6 hours ago
















Is bash a hard requirement, or is a zsh solution acceptable?

– Jeff Schaller
6 hours ago





Is bash a hard requirement, or is a zsh solution acceptable?

– Jeff Schaller
6 hours ago










2 Answers
2






active

oldest

votes


















2














For bash ≥ 4:



To read output of a command into an array line by line, you should use readarray:



readarray files < <(ls -1t *.jpg *.png | head -10)


... or mapfile:



mapfile -t files < <(ls -1t *.jpg *.png | head -10)



otherwise:



files=()
while IFS= read -r f; do
files+=( "$f" )
done < <(ls -1t *.jpg *.png | head -10)


See also.




But, filenames are allowed to have linebreaks, so for reading filenames you should rather use find and use delimiter instead of ls -1 which uses n delimiter:



files=()
while IFS= read -r -d $'' f; do
files+=("$f")
done < <(
find . -maxdepth 1 -type f
-regextype posix-extended -iregex ".*.(jpg|png)$"
-printf '%T@t%P'
| sort -nrz
| head -z -n 10
| cut -z -f2-
)





share|improve this answer
































    2














    The correct syntax is:



    list=($(ls -t *.jpg *.png | head -10))
    echo First element: $list[0]
    echo Last element: $list[9]


    However, this solution will have problems with file names containing space characters (or any white space in general).






    share|improve this answer










    New contributor




    FedonKadifeli is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.




















      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%2f512587%2fbash-command-to-create-array-with-the-10-most-recent-images-in-a-dir%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      For bash ≥ 4:



      To read output of a command into an array line by line, you should use readarray:



      readarray files < <(ls -1t *.jpg *.png | head -10)


      ... or mapfile:



      mapfile -t files < <(ls -1t *.jpg *.png | head -10)



      otherwise:



      files=()
      while IFS= read -r f; do
      files+=( "$f" )
      done < <(ls -1t *.jpg *.png | head -10)


      See also.




      But, filenames are allowed to have linebreaks, so for reading filenames you should rather use find and use delimiter instead of ls -1 which uses n delimiter:



      files=()
      while IFS= read -r -d $'' f; do
      files+=("$f")
      done < <(
      find . -maxdepth 1 -type f
      -regextype posix-extended -iregex ".*.(jpg|png)$"
      -printf '%T@t%P'
      | sort -nrz
      | head -z -n 10
      | cut -z -f2-
      )





      share|improve this answer





























        2














        For bash ≥ 4:



        To read output of a command into an array line by line, you should use readarray:



        readarray files < <(ls -1t *.jpg *.png | head -10)


        ... or mapfile:



        mapfile -t files < <(ls -1t *.jpg *.png | head -10)



        otherwise:



        files=()
        while IFS= read -r f; do
        files+=( "$f" )
        done < <(ls -1t *.jpg *.png | head -10)


        See also.




        But, filenames are allowed to have linebreaks, so for reading filenames you should rather use find and use delimiter instead of ls -1 which uses n delimiter:



        files=()
        while IFS= read -r -d $'' f; do
        files+=("$f")
        done < <(
        find . -maxdepth 1 -type f
        -regextype posix-extended -iregex ".*.(jpg|png)$"
        -printf '%T@t%P'
        | sort -nrz
        | head -z -n 10
        | cut -z -f2-
        )





        share|improve this answer



























          2












          2








          2







          For bash ≥ 4:



          To read output of a command into an array line by line, you should use readarray:



          readarray files < <(ls -1t *.jpg *.png | head -10)


          ... or mapfile:



          mapfile -t files < <(ls -1t *.jpg *.png | head -10)



          otherwise:



          files=()
          while IFS= read -r f; do
          files+=( "$f" )
          done < <(ls -1t *.jpg *.png | head -10)


          See also.




          But, filenames are allowed to have linebreaks, so for reading filenames you should rather use find and use delimiter instead of ls -1 which uses n delimiter:



          files=()
          while IFS= read -r -d $'' f; do
          files+=("$f")
          done < <(
          find . -maxdepth 1 -type f
          -regextype posix-extended -iregex ".*.(jpg|png)$"
          -printf '%T@t%P'
          | sort -nrz
          | head -z -n 10
          | cut -z -f2-
          )





          share|improve this answer















          For bash ≥ 4:



          To read output of a command into an array line by line, you should use readarray:



          readarray files < <(ls -1t *.jpg *.png | head -10)


          ... or mapfile:



          mapfile -t files < <(ls -1t *.jpg *.png | head -10)



          otherwise:



          files=()
          while IFS= read -r f; do
          files+=( "$f" )
          done < <(ls -1t *.jpg *.png | head -10)


          See also.




          But, filenames are allowed to have linebreaks, so for reading filenames you should rather use find and use delimiter instead of ls -1 which uses n delimiter:



          files=()
          while IFS= read -r -d $'' f; do
          files+=("$f")
          done < <(
          find . -maxdepth 1 -type f
          -regextype posix-extended -iregex ".*.(jpg|png)$"
          -printf '%T@t%P'
          | sort -nrz
          | head -z -n 10
          | cut -z -f2-
          )






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 7 hours ago

























          answered 8 hours ago









          RoVoRoVo

          3,876317




          3,876317























              2














              The correct syntax is:



              list=($(ls -t *.jpg *.png | head -10))
              echo First element: $list[0]
              echo Last element: $list[9]


              However, this solution will have problems with file names containing space characters (or any white space in general).






              share|improve this answer










              New contributor




              FedonKadifeli is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.
























                2














                The correct syntax is:



                list=($(ls -t *.jpg *.png | head -10))
                echo First element: $list[0]
                echo Last element: $list[9]


                However, this solution will have problems with file names containing space characters (or any white space in general).






                share|improve this answer










                New contributor




                FedonKadifeli is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.






















                  2












                  2








                  2







                  The correct syntax is:



                  list=($(ls -t *.jpg *.png | head -10))
                  echo First element: $list[0]
                  echo Last element: $list[9]


                  However, this solution will have problems with file names containing space characters (or any white space in general).






                  share|improve this answer










                  New contributor




                  FedonKadifeli is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.










                  The correct syntax is:



                  list=($(ls -t *.jpg *.png | head -10))
                  echo First element: $list[0]
                  echo Last element: $list[9]


                  However, this solution will have problems with file names containing space characters (or any white space in general).







                  share|improve this answer










                  New contributor




                  FedonKadifeli is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.









                  share|improve this answer



                  share|improve this answer








                  edited 4 hours ago





















                  New contributor




                  FedonKadifeli is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.









                  answered 8 hours ago









                  FedonKadifeliFedonKadifeli

                  315




                  315




                  New contributor




                  FedonKadifeli is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.





                  New contributor





                  FedonKadifeli is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.






                  FedonKadifeli is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.



























                      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%2f512587%2fbash-command-to-create-array-with-the-10-most-recent-images-in-a-dir%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

                      Ружовы пелікан Змест Знешні выгляд | Пашырэнне | Асаблівасці біялогіі | Літаратура | НавігацыяДагледжаная версіяправерана1 зменаДагледжаная версіяправерана1 змена/ 22697590 Сістэматыкана ВіківідахВыявына Вікісховішчы174693363011049382

                      ValueError: Error when checking input: expected conv2d_13_input to have shape (3, 150, 150) but got array with shape (150, 150, 3)2019 Community Moderator ElectionError when checking : expected dense_1_input to have shape (None, 5) but got array with shape (200, 1)Error 'Expected 2D array, got 1D array instead:'ValueError: Error when checking input: expected lstm_41_input to have 3 dimensions, but got array with shape (40000,100)ValueError: Error when checking target: expected dense_1 to have shape (7,) but got array with shape (1,)ValueError: Error when checking target: expected dense_2 to have shape (1,) but got array with shape (0,)Keras exception: ValueError: Error when checking input: expected conv2d_1_input to have shape (150, 150, 3) but got array with shape (256, 256, 3)Steps taking too long to completewhen checking input: expected dense_1_input to have shape (13328,) but got array with shape (317,)ValueError: Error when checking target: expected dense_3 to have shape (None, 1) but got array with shape (7715, 40000)Keras exception: Error when checking input: expected dense_input to have shape (2,) but got array with shape (1,)

                      Illegal assignment from SObject to ContactFetching String, Id from Map - Illegal Assignment Id to Field / ObjectError: Compile Error: Illegal assignment from String to BooleanError: List has no rows for assignment to SObjectError on Test Class - System.QueryException: List has no rows for assignment to SObjectRemote action problemDML requires SObject or SObject list type error“Illegal assignment from List to List”Test Class Fail: Batch Class: System.QueryException: List has no rows for assignment to SObjectMapping to a user'List has no rows for assignment to SObject' Mystery