Quantcast
Channel: Struggling with output of grep into an array - Unix & Linux Stack Exchange
Viewing all articles
Browse latest Browse all 2

Answer by Jesse_b for Struggling with output of grep into an array

$
0
0

First let me say sorry because I'm not exactly sure what your issue is at this time but I believe it is related to the way you are calling the array, and I have the following suggestions:

n=0
printf '%s,%s,%s\n' 'table_name' 'file_name' 'full_path' >> export_list.txt
while read -r table
do
    extract[$n]=$(egrep -ilrs "$table" /path/to/file | egrep -i tag | egrep -v backup)
    file_name=$(basename "${extract[$n]}")
    printf '%s,%s,%s\n' "$table" "$file_name" "${extract[$n]}" >> export_list.txt
    n=$((n+1))
done < table_list.txt
  1. The printf format string should always be separate from the actual content. (printf '%s,%s,%s\n' 'table_name' 'file_name' 'full_path')
  2. When using read you should almost always use the -r argument. This will allow it to read the \ escape character as a literal
  3. always double quote your variables. Because of this and this.
  4. There is a special syntax that must be used when referring to an array/array element. That is ${array[@]} (entire array) or ${array[0]} (first element in the array). When you call it as $array you will always get only the first element.
  5. Because of the above we need a way to ensure we are grabbing the correct array element on each iteration. For this I have added the n variable which will be incremented on each iteration of your loop.

note: There doesn't appear to be any need to use an array at all in this. Unless your code goes on to use extract in other places you could simply set it as a variable and reset it on each iteration of the loop.

Also note: Your question is tagged with "shell-script" but arrays are not specified by the POSIX standard so while most /bin/sh versions support them, there is no guarantee that yours does.


Viewing all articles
Browse latest Browse all 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>