0

I have the following piece of code:

v=`date "+%Y%m%d"`
awk -F, '{$2=$v;}1' OFS=, test.txt > test2.txt

where test.txt is my input file and test2.txt the output file.

The lines in test1.txt respect the following format: Unix,10,A

When I execute the above script, it doubles the first and last word from test.txt

digitalextremist
  • 5,932
  • 3
  • 41
  • 61
andcsie
  • 368
  • 2
  • 15
  • Does this answer your question? [How do I use shell variables in an awk script?](https://stackoverflow.com/questions/19075671/how-do-i-use-shell-variables-in-an-awk-script) – tripleee Nov 02 '19 at 16:01

3 Answers3

1

If the intention is to replace the second field with the value in $v, you will need to pass in the value to Awk somehow. As a separate process, Awk has no knowledge about the shell's internal variables.

awk -F, -v v="$v" '{$2=v}1' OFS=, test.txt > test2.txt

Notice also that the Awk variable's name is just v. To Awk, $v means the input field whose number is in the variable v.

tripleee
  • 158,107
  • 27
  • 234
  • 292
0

Like this

awk -F, '{$2=v;}1' OFS=, v=`date "+%Y%m%d"` file
Unix,20140109,A

You should not read variable inside awk
Assign them first, ten use them.

v=`date "+%Y%m%d"`
awk -F, '{$2=var;}1' OFS=, var="$v" file
Jotne
  • 39,326
  • 11
  • 49
  • 54
-1

I would recommend the non legacy syntax here:

v=$(date "+%Y%m%d")

then you can use any of these awk invocations:

awk -F, -v v="$v" '{$2=v}1' OFS=, test.txt > test2.txt
awk -F, '{$2=v}1' OFS=, v="$v" test.txt > test2.txt
awk -F, '{$2="'$v'"}1' OFS=, test.txt > test2.txt

Alternatively, if you don't need the v variable later in the shell, you can run the date command from inside awk with either:

awk -F, 'BEGIN{"date \"+%Y%m%d\""|getline v}{$2=v}1' OFS=, test.txt > test2.txt

or

awk -F, 'BEGIN{v="'$(date "+%Y%m%d")'"}{$2=v}1' OFS=, test.txt > test2.txt 

or the inefficient

awk -F, '{$2="'$(date "+%Y%m%d")'"}1' OFS=, test.txt > test2.txt 
jlliagre
  • 28,380
  • 6
  • 58
  • 69