Iterate through list of filenames in order they were created in bash

前端 未结 8 1752
深忆病人
深忆病人 2020-12-05 19:27

Parsing output of ls to iterate through list of files is bad. So how should I go about iterating through list of files in order by which they were first created

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 19:49

    I've just found a way to do it with bash and ls (GNU).
    Suppose you want to iterate through the filenames sorted by modification time (-t):

    while read -r fname; do
        fname=${fname:1:((${#fname}-2))} # remove the leading and trailing "
        fname=${fname//\\\"/\"}          # removed the \ before any embedded "
        fname=$(echo -e "$fname")        # interpret the escaped characters
        file "$fname"                    # replace (YOU) `file` with anything
    done < <(ls -At --quoting-style=c)
    

    Explanation

    Given some filenames with special characters, this is the ls output:

    $ ls -A
     filename with spaces   .hidden_filename  filename?with_a_tab  filename?with_a_newline  filename_"with_double_quotes"
    
    $ ls -At --quoting-style=c
    ".hidden_filename"  " filename with spaces "  "filename_\"with_double_quotes\""  "filename\nwith_a_newline"  "filename\twith_a_tab"
    

    So you have to process a little each filename to get the actual one. Recalling:

    ${fname:1:((${#fname}-2))} # remove the leading and trailing "
    # ".hidden_filename" -> .hidden_filename
    ${fname//\\\"/\"}          # removed the \ before any embedded "
    # filename_\"with_double_quotes\" -> filename_"with_double_quotes"
    $(echo -e "$fname")        # interpret the escaped characters
    # filename\twith_a_tab -> filename     with_a_tab
    

    Example

    $ ./script.sh
    .hidden_filename: empty
     filename with spaces : empty
    filename_"with_double_quotes": empty
    filename
    with_a_newline: empty
    filename    with_a_tab: empty
    

    As seen, file (or the command you want) interprets well each filename.

提交回复
热议问题