0

I have a file which contains timestamp and date in the second column. If the line contains one of the word then it need to be replace like below.

File:
a smallint
b timestamp
c date
d varchar

O/P:
a smallint
dateformat(b,'YYYY-MM-DD HH:NN:SS.sss')
dateformat(c.'YYYY-MM-DD')
d varchar

If I execute this below command as a single awk then I am getting output but if I use else condition then I am getting error.

awk '{if ($2=="timestamp") {$3="dataformat("; }; print $3 $1 ",'\''YYYY-MM-DD HH'\:'NN'\:'SS'\.'sss)" else ($2=="date") {$3="dataformat("; }; print $3 $1 ",'\''YYYY-MM-DD)" }' test.out 

Error:

awk: {if ($2=="timestamp") {$3="dataformat("; }; print $3 $1 ",'YYYY-MM-DD HH:NN:SS.sss)" else ($2=="date") {$3="dataformat("; }; print $3 $1 ",'YYYY-MM-DD)" }
awk: ^ syntax error

2 Answers 2

2

I would write:

awk -v q="'" '
    $2 == "timestamp" { $0 = sprintf("dateformat(%s, "q"YYYY-MM-DD HH:NN:SS.sss"q")", $1) }
    $2 == "date"      { $0 = sprintf("dateformat(%s, "q"YYYY-MM-DD"q")", $1) }
                      { print }
' file
2
  • Great call on the single quotes and using q for that! Commented Oct 23, 2018 at 3:01
  • @glenn jackman and it worked. Thanks for your help. Commented Oct 23, 2018 at 3:05
1

Let me wrap the lines in your command first:

awk '
    {
        if ($2=="timestamp") {
            $3="dataformat("; 
        };
        print $3 $1 ",'\''YYYY-MM-DD HH'\:'NN'\:'SS'\.'sss)"
        else ($2=="date") {
            $3="dataformat("; 
        };
        print $3 $1 ",'\''YYYY-MM-DD)"
    }
' test.out 

So, two problems there, one is that the else clause does not align with the if clause (there's a print command outside it) and the second is that the else clause doesn't take a condition, you want to use else if instead.

So maybe this is what was intended instead?

awk '
    {
        if ($2=="timestamp") {
            $3="dataformat("
            print $3 $1 ",'\''YYYY-MM-DD HH'\:'NN'\:'SS'\.'sss)"
        } else if ($2=="date") {
            $3="dataformat("
            print $3 $1 ",'\''YYYY-MM-DD)"
        }
    }
' test.out 

Also not sure what you want to do about the other lines that do not match... You can add an else to the end that does a simple print (defaults to printing the unmodified line), or maybe a print of specific fields.

Please note that the formatting is helpful in seeing how your blocks nest! This is perfectly valid syntax, the shell takes multi-line single-quoted strings just fine and awk will also be pretty happy with them. I recommend you use that more readable formatting of your awk scripts.

1
  • 1
    Ha, I did exactly what you did: adding newlines and indentation to the OP's code. Nice. Commented Oct 23, 2018 at 2:50

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.