klex52s
klex52s

Reputation: 437

Store Output of Grep In Array

I have netCDF files in two directories that I want to ultimately find a single variable in and compare, and if not equal I want to remove both files. What I have so far:

dir1=(/working/test/temp1/*.nc)
dir2=(/working/test/temp2/*.nc)

Here I'm trying to store the output of grep into an array. I found these methods on the site, but neither to work.

for ((i = 0; i < ${#dir1[@]}; ++i)); do
  dir1_arr=($(ncdump -h "$dir1" | grep "Temperature = "))
done

for i in $dir1; do
dir1_arr=($(ncdump -h "$i" | grep "Granules = "))
done

I'm not sure if this is the right approach, but I want to then compare the granule values that should be stored in two separate arrays, then delete the corresponding files if the granules don't match. First I need to get past this step of storing the output of grep in array.

Upvotes: 1

Views: 1125

Answers (1)

Armali
Armali

Reputation: 19375

All presented attempts lack quoting of the $(…), which is essential because the grep output contains multiple words. See the end of this answer for a solution. In addition, there are other errors:


for ((i = 0; i < ${#dir1[@]}; ++i)); do
  dir1_arr=($(ncdump -h "$dir1" | grep "Temperature = "))
done

This didn't work because in the loop body

  • you used $dir1 instead of ${dir1[i]}
  • you used dir1_arr= instead of dir1_arr+=

for i in $dir1; do
dir1_arr=($(ncdump -h "$i" | grep "Granules = "))
done

This didn't work because

  • in the for command head you used $dir1 instead of "${dir1[@]}"
  • in the loop body you used dir1_arr= instead of dir1_arr+=

dir1_arr=(); for d in /working/test/temp1/*.nc; do dir1_arr+=($(ncdump -h "$d" | grep "Temperature = ")); done

This didn't work because of the wrongly absolute path /….


A correct version is

dir1_arr=()
for d in working/test/temp1/*.nc
do  dir1_arr+=("$(ncdump -h $d | grep 'Granules =')")
done

Upvotes: 1

Related Questions