Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grep output lines in array

Tags:

linux

grep

bash

I'm trying to put my grep output lines into an array as elements.

The output after grep (files are stored in /asd folder for example)

test.mp4
test2.mp4

So here's how it should be at the end:

arr_name[0] = test.mp4
arr_name[1] = test2.mp4

Here's my code so far:

arr_name=( $(cd ~/asd; ls -tr | grep -v total | head -2) )

Can you please help me to resolve the mistake?

like image 894
MNedelchev Avatar asked Apr 29 '26 18:04

MNedelchev


1 Answers

You don't need grep here and avoid parsing output of ls by using -I option of ls.

# To list all files except *total*
ls -I '*total*' -tr

# to read all the listed entries in an array
mapfile -t  arr < <(ls -I '*total*' -tr)

# to get first 2 entries
echo "${arr[@]:0:2}"

# to store 2 entries in an array
parr=("${arr[@]:0:2}")

# check your results
declare -p parr
like image 162
anubhava Avatar answered May 02 '26 15:05

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!