1

I want to declare a variable called variableToUse which holds the file name path. I want to append file name with today's date. Below code is in myAWK.awk

$bash: cat myAWK.awk
    BEGIN{
    today="date +%Y%m%d";
    variableToUse=/MainDir/MainDir1/MainDir2/OutputFile_today.xml
    }

    /<record / { i=1 }
    i { a[i++]=$0 }
    /<\/record>/ {
        if (found) {
             print a[i] >> variableToUse
        }
    }

I am getting syntax error at OutputFile_today.xml.

How to use variable value?

2 Answers 2

1
  • You should quote the variables properly

Example

$ awk 'BEGIN{variableToUse="/MainDir/MainDir1/MainDir2/OutputFile_today.xml"; print variableToUse}'
/MainDir/MainDir1/MainDir2/OutputFile_today.xml
  • To get the current date you can use strftime

Example

$ awk 'BEGIN{today="date +%Y%m%d";variableToUse="/MainDir/MainDir1/MainDir2/OutputFile_"strftime("%Y%m%d")".xml"; print variableToUse}'
/MainDir/MainDir1/MainDir2/OutputFile_20160205.xml
Sign up to request clarification or add additional context in comments.

2 Comments

The above code prints /MainDir/MainDir1/MainDir2/OutputFile_today.xml. But I want, /MainDir/MainDir1/MainDir2/OutputFile_20160205.xml
@user2488578 Sorry for that, I just noticed the error while creating the variable. updated the answer to get the today as required using strftime
1

Have your awk script like this:

BEGIN {
   today="date +%Y%m%d";
   variableToUse="/MainDir/MainDir1/MainDir2/OutputFile_" today ".xml"
}

/<record / { i=1 }
i { a[i++]=$0 }
/<\/record>/ {
    if (found) {
         print a[i] >> variableToUse
    }
}

btw there are couple of other issues: - I don't see found getting set anywhere in this script. - today="date +%Y%m%d" will not execute date command. It just assigns literaldate +%Y%m%dtotodayvariable. If you want to executedate` command then use:

awk -v today="$(date '+%Y%m%d')" -f myAWK.awk

and remove today= line from BEGIN block.

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.