tags:

views:

623

answers:

4

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.

+6  A: 
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)

Ayman Hourieh
That prints the first 10 characters, right?
No, it prints the first 10 elements of an array. The array contains filenames as items.
Ayman Hourieh
Your reference to the ABS is bad. They don't use quotes (typical ABS), thus causing wordsplitting bugs on the expanded filename. ABS is full of such hidden bugs causing anyone who learns from it (except for you, apparantly, you do it right) to inherit those bugs! I'd refer to http://mywiki.wooledge.org/BashGuide/TheBasics/Arrays instead.
lhunath
ABS contains a wealth of useful information in my opinion. But in this case, the link you provided is more relevant so I added it to my answer.
Ayman Hourieh
You should be more clear on FILE=(*); maybe use the original command sub: FILES=($(ls))
guns
@guns, why spawn an `ls` process when you can use globbing?
Ayman Hourieh
@guns: That also doesn't do the right thing when the filenames contain spaces.
ephemient
A: 
FILES=$(ls)
echo $FILES | fmt -1 | head -10
sunny256
Does not work as expected if there are files with spaces in their names.
Ayman Hourieh
I'm aware of that, but thought dehmann wanted to use this specific method, so I reckoned spaces wouldn't be a problem.BTW, did you meanFILES=(*)echo "${FILES[@]:0:10}"? That works better here.
sunny256
Indeed, I correct this. Thanks!
Ayman Hourieh
+1  A: 
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.

FeatureCreep
+1  A: 

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

Idelic