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,952
  • 3
  • 43
  • 62
andcsie
  • 398
  • 2
  • 17
  • 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
  • 175,061
  • 34
  • 275
  • 318
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
  • 40,548
  • 12
  • 51
  • 55
-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
  • 29,783
  • 6
  • 61
  • 72