Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

syntax

bash

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

For example, the first 10 files in this list:

FILES=$(ls)

UPDATE: I forgot to say that I want to print the elements on one line, just like when you print the whole list with echo $FILES.

like image 887
Frank Avatar asked May 20 '09 00:05

Frank


People also ask

How do I print N in bash?

Printing Newline in Bash The most common way is to use the echo command. However, the printf command also works fine. Using the backslash character for newline “\n” is the conventional way.

How do you display the first element of an array in bash?

To get the first element (10) from the array, we can use the subscript [ ] syntax by passing an index 0 . In bash arrays are zero-indexed, so the first element index is 0 .

What is $_ in bash?

$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.

How do I echo list in bash?

How to Echo a Bash Array? To echo an array, use the format echo ${Array[0]}. Array is your array name, and 0 is the index or the key if you are echoing an associative array. You can also use @ or * symbols instead of an index to print the entire array.


1 Answers

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)

like image 129
Ayman Hourieh Avatar answered Oct 10 '22 17:10

Ayman Hourieh