Grep output to array

Guys how can i do this job

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

I do not want to store the array in any temporary variable. How can we work directly with this array.

to get the 1st element of this array

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

+8
arrays bash grep
source share
5 answers

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

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

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

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

but this will not cause each line of the grep output file to be split into a separate array element.

If you need whole lines instead of words, you can use head and tail for this task, for example:

 `find /xyz/abc/music/ |grep def | head -n line_number | tail -n 1` 
+9
source share

Place a 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]} 
+16
source share

Although a little late, the best solution should be the answer from Ray, but you will have to rewrite the default IFS environment variable for IFN for the new line to enter the complete lines as an array field. After filling the array, you should switch the IFS to the original value. I will reveal the 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}
# 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

+3
source share

it will work

 array_name=(`find directorypath | grep "string" | awk -F "\n" '{print $1}'`) echo $array_name 
+1
source share

Do you want to get the first line of output?

 find /xyz/abc/music/ |grep def|head 1 
0
source share

All Articles