3

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?

3
  • Looks okay; how are you testing to see if it is working? echo ${arr_name[0]} etc... should work. Commented Jul 2, 2016 at 17:10
  • When i run the script it says Syntax error: "(" unexpected for the line where the array is Commented Jul 2, 2016 at 19:52
  • edit your question to include a minimal reproducible example. Commented Jul 2, 2016 at 21:38

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

Nice. Could you elaborate on how mapfile -t arr < <(ls -I '*total*' -tr) works here?
I used mapfile to populate the array with output of ls command. Command substitution may also work as an Annemarie but will break if file names have spaces.
1

You can just set

IFS='
'

Then the lines will be saved correctly

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.