In bash, how can I print the first n elements of a list?

后端 未结 8 1352
死守一世寂寞
死守一世寂寞 2021-02-19 20:00

In bash, how can I print the first n elements of a list?

For example, the first 10 files in this list:

FILES=$(ls)
相关标签:
8条回答
  • 2021-02-19 20:34

    to do it interactively:

    set $FILES && eval eval echo \\\${1..10}

    to run it as a script, create foo.sh with contents

    N=$1; shift; eval eval echo \\\${1..$N}

    and run it as

    bash foo.sh 10 $FILES

    0 讨论(0)
  • 2021-02-19 20:35

    Why not just this to print the first 50 files:

    ls -1 | head -50
    
    0 讨论(0)
  • 2021-02-19 20:35
    FILE="$(ls | head -1)"
    

    Handled spaces in filenames correctly too when I tried it.

    0 讨论(0)
  • 2021-02-19 20:41

    An addition to the answer of "Ayman Hourieh" and "Shawn Chin", in case it is needed for something else than content of a directory.

    In newer version of bash you can use mapfile to store the directory in an array. See help mapfile

    mapfile -t files_in_dir < <( ls )
    

    If you want it completely in bash use printf "%s\n" * instead of ls, or just replace ls with any other command you need.

    Now you can access the array as usual and get the data you need.

    First element:

    ${files_in_dir[0]}
    

    Last element (do not forget space after ":" ):

    ${files_in_dir[@]: -1}
    

    Range e.g. from 10 to 20:

    ${files_in_dir[@]:10:20}
    

    Attention for large directories, this is way more memory consuming than the other solutions.

    0 讨论(0)
  • 2021-02-19 20:42
    FILES=$(ls)
    echo $FILES | fmt -1 | head -10
    
    0 讨论(0)
  • 2021-02-19 20:46

    My way would be:

    ls | head -10 | tr "\n" " "
    

    This will print the first 10 lines returned by ls, and then tr replaces all line breaks with spaces. Output will be on a single line.

    0 讨论(0)
提交回复
热议问题