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

后端 未结 8 1355
死守一世寂寞
死守一世寂寞 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: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.

提交回复
热议问题