1

I'm trying to extract dates from a .nc file and I wanted to write a script to automate the process by using a .txt file, the data looks like this:

1995 04 05  
1995 06 12  
1995 06 30  
1995 07 16  
1995 07 19  
1995 07 20  
1995 07 28  
1996 03 09  
1996 04 25  
1996 08 13  

I want to assign a variable for years, months and days separately e.g. , so that It would take the date from each line as input it in a command like this:

cdo seltimestep,$DD "mon_$MM.nc" "/Desktop/2020/output/$YYYY-$MM-$DD.nc"

I previously made a script similar to this but I had to input each date manually.

ClimateUnboxed
  • 7,106
  • 3
  • 41
  • 86
  • What you are making sounds like a program, not a script. Is this script required to be bash by your manager? If not, try Python and you'll save lot's of headaches with timestamps. – Bart Mensfort Sep 15 '20 at 11:05
  • Not really, It's just that I have no experience with python as opposed to bash. – ali.almannai Sep 16 '20 at 04:48

3 Answers3

3

You can read input file line by line and then use bash array to split the dates.

#!/bin/bash

while read -r line; do
  dateArray=( $line )
  echo "YYYY: ${dateArray[0]}, MM: ${dateArray[1]}, DD: ${dateArray[2]}"
done < input.file
rcwnd_cz
  • 909
  • 6
  • 18
2

Using awk:

awk '{printf("YYYY: %04d, MM: %02d, DD: %02d\n", $1, $2, $3)}' input.txt

The actual awk program is very straightforward, printing formatted fields of each record line:

{
  printf("YYYY: %04d, MM: %02d, DD: %02d\n", $1, $2, $3)
}
Léa Gris
  • 17,497
  • 4
  • 32
  • 41
0

Read can create all needed vars from line at once

while read  -r   year         month       day; do
    echo "Year: $year Month: $month Day: $day"
done < file
Ivan
  • 6,188
  • 1
  • 16
  • 23