2

There is a command which prints out to file range of values from CSV file:

date1var=mm/dd/yyyy hh:mm:ss
date2var=mm/dd/yyyy hh:mm:ss
awk -F, -v d1var="$date1var" -v d2var="$date2var" '$1 > d1var && $1 <= d2var {print $0 }' OFS=, plot_data.csv > graph1.csv

I'm just guessing if it's possible to include my variables to the output filename?

Final name of the file should be similar to:

graph_d1var-d2var.csv

Any ideas?

3 Answers 3

2

You can redirect the output of print command to a file name, like:

awk -F, -v d1var="$date1_var" -v d2var="$date2var" '
    $1 > d1var && $1 <= d2var {
        print > ("graph_" d1var "-" d2var ".csv") 
    }' 
OFS=, plot_data.csv

This uses the values of d1var and d2var to create the name of the output file. If you want the name of the variables, surround the whole name in double quotes.

Sign up to request clarification or add additional context in comments.

2 Comments

print $0 > "graph_" d1var "-" d2var ".csv" is ambiguous, some awks will parse it as (print $0> "graph_") d1var "-" d2var ".csv". You always need to parenthesize string concatenation on the right side of a redirection symbol: print > ("graph_" d1var "-" d2var ".csv"). I dropped the unnecessary $0 too.
thanks Birei & @EdMorton, I did not know the concatenation trick, very useful!
2

Let the shell handle it: you're starting with shell variables after all

date1var=mm/dd/yyyy hh:mm:ss
date2var=mm/dd/yyyy hh:mm:ss
awk -F, -v OFS=, -v d1var="$date1var" \
                 -v d2var="$date2var" \
'
# awk script is unchanged
' plot_data.csv > "graph1_${date1var}-${date2var}.csv"

Comments

1
#!/bin/bash
date1var="1234"
date2var="5678"
awk -F, -v d1="$date1var" -v d2="$date2var" '{print > ("graph" d1 "-" d2 ".txt")}' OFS=, plot_data.csv

Note that you can't compare date strings in awk like you are trying to do. You also have a typo, in that you have written date1_var with an underscore whereas you have used date1var without an underscore further on.

I guess the short answer is that you can print to a named file with print > "filename" and that you can concatenate (join) strings by placing them beside each other like this string2 = string1 "and" string3;

2 Comments

Oh! Thank you! I fixed typo. Could you please also explain why can't I compare date strings this way? It looks like it's working. I know that the date format I'm using is terrible but that the incoming CSV file format...
print $0> "graph" d1 "-" d2 ".txt" is ambiguous, some awks will parse it as (print $0> "graph") d1 "-" d2 ".txt". You always need to parenthesize string concatenation on the right side of a redirection symbol: print > ("graph" d1 "-" d2 ".txt"). I dropped the unnecessary $0 too.

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.