| 1 | #!/bin/bash |
|---|
| 2 | ################################################################ |
|---|
| 3 | ### Script to concatenate "diagpem.nc" outputs into one file ### |
|---|
| 4 | ################################################################ |
|---|
| 5 | |
|---|
| 6 | # Output file name |
|---|
| 7 | output_file="diagpem_concat.nc" |
|---|
| 8 | |
|---|
| 9 | # Frequency of PEM outputs |
|---|
| 10 | ecritpem=1 |
|---|
| 11 | |
|---|
| 12 | # Number of GCM calls between each PEM call |
|---|
| 13 | nGCM=2 |
|---|
| 14 | |
|---|
| 15 | # List of NetCDF files to concatenate |
|---|
| 16 | directory="diags" |
|---|
| 17 | files=($directory/diagpem*.nc) |
|---|
| 18 | output_file=($directory/$output_file) |
|---|
| 19 | |
|---|
| 20 | # Checking if everything is ok |
|---|
| 21 | if [ ! -d "$directory" ]; then |
|---|
| 22 | echo "Error: directory \"$diags\" not found!" |
|---|
| 23 | exit 1 |
|---|
| 24 | fi |
|---|
| 25 | if [ ${#files[@]} -lt 2 ]; then |
|---|
| 26 | echo "Error: there are not enough files for concatenation!" |
|---|
| 27 | exit 1 |
|---|
| 28 | fi |
|---|
| 29 | if [ -f "$output_file" ]; then |
|---|
| 30 | rm $output_file |
|---|
| 31 | fi |
|---|
| 32 | |
|---|
| 33 | # Loop to concatenate the NetCDF files |
|---|
| 34 | newTime=$((nGCM + 1)) |
|---|
| 35 | for file in "${files[@]}"; do |
|---|
| 36 | # Extract the 'Time' variable into a temporary file |
|---|
| 37 | ncks -v Time "$file" > tmp_Time.txt |
|---|
| 38 | |
|---|
| 39 | # Extract the 'data' block containing the Time values |
|---|
| 40 | data_block=$(awk '/data:/ {flag=1} flag; /\}/ {flag=0}' tmp_Time.txt | sed '1d;$d') |
|---|
| 41 | data_block=$(echo "$data_block" | sed -e 's/^[ \t]*//') |
|---|
| 42 | data_block=$(echo "$data_block" | sed 's/Time =//') |
|---|
| 43 | data_block=$(echo "$data_block" | sed 's/;$//') |
|---|
| 44 | IFS=', ' read -ra Time_values <<< "$data_block" |
|---|
| 45 | |
|---|
| 46 | # Remove the temporary file |
|---|
| 47 | rm tmp_Time.txt |
|---|
| 48 | |
|---|
| 49 | # Updating the variable 'Time' with the number of the year |
|---|
| 50 | for ((i=0; i < ${#Time_values[@]}; i++)); do |
|---|
| 51 | ncap2 -O -s "Time($i)=$newTime" $file $file |
|---|
| 52 | newTime=$((newTime + ecritpem)) |
|---|
| 53 | done |
|---|
| 54 | |
|---|
| 55 | # Concatenate the NetCDF file to the output |
|---|
| 56 | if [ ! -f "$output_file" ]; then |
|---|
| 57 | cp $file $output_file |
|---|
| 58 | else |
|---|
| 59 | ncrcat -O $output_file $file -o $output_file |
|---|
| 60 | fi |
|---|
| 61 | newTime=$((newTime + nGCM)) |
|---|
| 62 | done |
|---|
| 63 | |
|---|
| 64 | echo "Concatenation of \"$directory/diagpem*.nc\" files into \"$output_file\" is complete!" |
|---|