Saturday, May 23, 2009

Print first n elements from list in bash


To move first 3 .log files to the "bak" directory.

The ways:

$ ls *.log | sed '1,3 !d' | xargs -i mv {} bak/

Same as

$ ls *.log | sed -n '1,3 p' | xargs -i mv {} bak/

Same as

$ ls *.log | head -3 | xargs -i mv {} bak/

Same as

$ ls *.log | head -3 | while read file
mv $file bak/

And using bash array:

$ FILES=(*.log)
$ mv "${FILES[@]:0:3}" bak/


Nathan said...

Good One.
I really like the array's way , using substrings.

rattus said...

Sorry for the late comment. Just wanted to say thanks for showing the approach using Bash arrays.

rattus said...

Of course, in order to sort by anything but filename one would have to use e.g. FILES=($(ls -t *.log)) to sort by time.

© Jadu Saikia