Jonathan Ilambo
Jonathan Ilambo

Reputation: 329

Put a value comes from a file in a global variable (AWK script)

I have several files (.csv) in entry of my script awk. I separate these files in other files (.csv) that i insert the data of these files into a database with help of a sql loader (oracle).

I want to put a value in the file to put in a global variable which I can use everywhere in my awk script.

Do you have ideas how I can create a global variable with in an AWK script.

Thank you in advance

Example : file.csv

NUMBER1;TEXT1;DATE1
NUMBER2;TEXT2;DATE1
NUMBER3;TEXT3;DATE1
NUMBER4;TEXT4;DATE1
NUMBER5;TEXT5;

I want to create a new file (result.csv) with these informations

NUMBER1;DATE1
NUMBER2;DATE1
NUMBER3;DATE1
NUMBER4;DATE1
NUMBER5;DATE1

Upvotes: 0

Views: 470

Answers (3)

Ed Morton
Ed Morton

Reputation: 204258

It looks like this is what you are trying to do:

$ awk 'BEGIN{FS=OFS=";"} NR==1{date=$NF} {print $1,date}' file
NUMBER1;DATE1
NUMBER2;DATE1
NUMBER3;DATE1
NUMBER4;DATE1
NUMBER5;DATE1

Get the book "Effective Awk Programming", 4th Edition, by Arnold Robbins.

Upvotes: 2

karakfa
karakfa

Reputation: 67537

You can define variables for your awk script with -v option. For example, assume you have the env variable $DATE.

$ DATE=$(date)
$ awk -v date="$DATE" '{print date}' <<< "ignore"
Mon Sep 14 10:27:59 EDT 2015

Since your example file.csv already has all the fields I'm not sure what variable you want to pass to the script. However, assuming that you want the first field from file.csv and generate result.csv with a date variable you can do this

awk -F";" -v OFS=";" -v date="$DATE" '{print $1, date}' file.csv > result.csv

Upvotes: 1

mikeb
mikeb

Reputation: 11287

Look into BEGIN and END for awk:

awk 'BEGIN { globalvar = "x" } {} '

The begin block gets executed once, so set your variable there.

See here: http://code.linuxnix.com/2013/02/awk-scripting-10-begin-and-end-block-examples.html

Upvotes: 1

Related Questions