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

后端 未结 8 1353
死守一世寂寞
死守一世寂寞 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:47
    FILES=(*)
    echo "${FILES[@]:0:10}"
    

    Should work correctly even if there are spaces in filenames.

    FILES=$(ls) creates a string variable. FILES=(*) creates an array. See this page for more examples on using arrays in bash. (thanks lhunath)

    0 讨论(0)
  • 2021-02-19 20:52
    echo $FILES | awk '{for (i = 1; i <= 10; i++) {print $i}}'
    

    Edit: AAh, missed your comment that you needed them on one line...

    echo $FILES | awk '{for (i = 1; i <= 10; i++) {printf "%s ", $i}}'
    

    That one does that.

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