1

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.

9
  • When I do echo ${dir1[@]}, nothing prints to the screen. Commented Aug 2, 2016 at 15:58
  • Your dir1 array is empty. Is the directory you care about really the absolute path /working/... or should that just be the relative path working/...? Commented Aug 2, 2016 at 16:30
  • @EdMorton I want the array to contain the netCDF files in that directory path. It should probably be the relative path. Commented Aug 2, 2016 at 16:39
  • @anubhava yes echoing that does show all files Commented Aug 2, 2016 at 16:42
  • Does echo "${dir1[@]}" work? Commented Aug 2, 2016 at 16:48

1 Answer 1

1

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

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.