14

Guys How can I make this work

`find /xyz/abc/music/ |grep def`

I don't want to store the array in any temporary variable. How can we directly operate on this array.

so to get the 1st element of that array

echo ${$(`find /xyz/abc/music/ |grep def`)[0]} Please help me How I can achieve this

newbietester
  • 153
  • 1
  • 1
  • 4

5 Answers5

31

Put the call to find in array brackets

X=( $(find /xyz/abc/music/ | grep def) )
echo ${X[1]}
echo ${X[2]}
echo ${X[3]}
echo ${X[4]}
Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • 2
    This is the one for me. I've looked at quite a few Q's on SO about getting grep results into an array and I find the word 'elegant' showing up a lot in a negative context as an unattainable criterion… this is pretty much the exemplar of a solution that actually meets the definition of elegant _and_ accomplishes the task in one line. Most of the answers are "There's not a good way to do this"… "of a lot of roundabout methods…" Thank you! +1 – om01 May 19 '13 at 16:49
  • echo$(om01 thoughts) :) – The_Lost_Avatar Nov 14 '14 at 06:33
13

If you just need the first element (or rather line), you can use head:

`find /xyz/abc/music/ |grep def | head -n 1`

If you need access to arbitrary elements, you can store the array first, and then retrieve the element:

arr=(`find /xyz/abc/music/ |grep def`)
echo ${arr[n]}

but this will not put each line of grep output into a separate element of an array.

If you care for whole lines instead of words, you can use head and tail for this task, like so:

`find /xyz/abc/music/ |grep def | head -n line_number | tail -n 1`
Michał Trybus
  • 11,526
  • 3
  • 30
  • 42
7

Even though a bit late, the best solution should be the answer from Ray, but you'd have to overwrite the default field separator environment variable IFS to newline for taking complete lines as an array field. After filling your array, you should switch IFS back to the original value. I'll expand Rays solution:



    # keep original IFS Setting
    IFS_BAK=${IFS}
    # note the line break between the two quotes, do not add any whitespace, 
    # just press enter and close the quotes (escape sequence "\n" for newline won't do)
    IFS="
    "
    X=( $(find /xyz/abc/music/ | grep def) )
    echo ${X[1]}
    echo ${X[2]}
    echo ${X[3]}
    echo ${X[4]}
    # set IFS back to normal..
    IFS=${IFS_BAK}


Hope this helps

Markus Natter
  • 71
  • 1
  • 1
  • Good point, especially if you have blanks in your filenames. A somewhat nicer way to set IFS, however, is by using the syntax IFS=$'\n'. – Elmar Zander Feb 15 '14 at 15:23
1

this will work

array_name=(`find directorypath | grep "string" | awk -F "\n" '{print $1}'`)
echo $array_name
zessx
  • 68,042
  • 28
  • 135
  • 158
afsal thaj
  • 11
  • 1
0

Do you mean to get the first line of the output?

find /xyz/abc/music/ |grep def|head 1
Kevin
  • 53,822
  • 15
  • 101
  • 132
Leon
  • 2,810
  • 5
  • 21
  • 32