0

I am new in shell/bash scripting. I want to extract data from multiple netcdf files using the bash or shell script. Each file contains a time series of temperature values. For example:

FileA.nc contains 20 20 21 22 23 24
FileB.nc contains 23 24 25 26 27 24
FileC.nc contains 21 20 19 18 22 23

I want to extract the values per file and merge the results of the three files. The output should look like this saved as a csv file.

A 20 20 21 22 23 24
B 23 24 25 26 27 24
C 21 20 19 18 22 23

What is the easiest way to do this? Many thanks in advance for the help.

3
  • Is A,B and so on single character stuff? Commented Jul 29, 2016 at 6:21
  • My awk script gives the expected output but it doesn't look like the valid csv file. Commented Jul 29, 2016 at 7:27
  • Expected output differs from the contents of the fileC.nc. Commented Jul 29, 2016 at 7:49

3 Answers 3

3

You can proceed as-

for i in {A..C}
do 
echo -n "$i " >> master_file
cat File"$i".nc >> master_file
done 

Now you'll have a huge file with appended individual files. Now to make spaces into commas (if you want a .csv format)

sed -i 's/ /,/g' master_file
Sign up to request clarification or add additional context in comments.

6 Comments

Your question suggested that the files only had the temperature data. You need to be clearer about what your individual input files contain. Please edit your question.
Many Thanks for the help, I deleted my previous comment here. I was processing the wrong file a while ago.This is already working for my problem.Many thanks again
If it's a valid solution then please 'accept' it as an answer.
The result should also contain a part of the file-name ie A in FileA.nc and so. This solution doesn't implement it.
@sjsam Yup, fair enough. Edited it to make it exactly what OP wanted.
|
2

awk is your friend :

$ arry=( file{A..C}.nc ) # store all the filenames in an array
$ # Then feed all the files to awk like below
$ awk '{printf "%s %s\n",gensub(/file(.)\.nc/,"\\1","1",FILENAME),$0}' "${arry[@]}" >newfile
$ cat newfile 
A 20 20 21 22 23 24
B 23 24 25 26 27 24
C 21 20 19 18 22 23

Note

This requires you have [ gnu awk ] which I suppose you already have.

Comments

1

In AWK:

$ awk '{gsub(/^file|\.nc$/,"",FILENAME); print FILENAME,$0}' file*.nc
A 20 20 21 22 23 24
B 23 24 25 26 27 24
C 21 20 19 18 22 23

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.