2

I am trying to input tofile2 from file1 so that each line in file2 is the first field of each file1 line, followed by a space and the current time.

E.g.

IN-X_4096_20140802_121306_007 `random text`
IN-X_4096_20140802_133431_012 `random text`
IN-A_6046_20130613_165426 `random text`
IN-A_6046_20130613_165426 `random text`
IN-X_4096_20140802_133431_014 `random text`

becomes

IN-X_4096_20140802_121306_007 14:24:32
IN-X_4096_20140802_133431_012 14:24:32
IN-A_6046_20130613_165426 14:24:32
IN-A_6046_20130613_165426 14:24:32
IN-X_4096_20140802_133431_014 14:24:32

But what I am getting is

IN-X_4096_20140802_121306_007 0
IN-X_4096_20140802_133431_012 0
IN-A_6046_20130613_165426 0
IN-A_6046_20130613_165426 0
IN-X_4096_20140802_133431_014 0

The code I am using is:

awk '{b=$1" "date +"%r"; print b >"file2.csv" }' file1.csv

The same thing happens when I use "%T"

kvantour
  • 25,269
  • 4
  • 47
  • 72
ZakS
  • 1,073
  • 3
  • 15
  • 27

2 Answers2

3

Written like that, date is interpreted as a variable name. As it is unset, it evaluates to "" or 0 depending on the context. The + operator after it means that it is evaluated in an arithmetic context, therefore it takes the value 0.

To pass the value of date +%r to your awk script, use either of these approaches:

# the time when the script was run, doesn't change
awk -v time="$(date +%r)" '{ print time }' file1.csv

# the time when each record is read
awk '{ cmd = "date +%r"; cmd | getline time; print time; close(cmd) }' file1.csv
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
2

From your question it is not clear which behaviour you are expecting, but here are two Gnu awk solutions:

  1. The computed date-time string has to be constant during the entire run of the command:

    awk 'BEGIN{t=strftime("%r")}{ print $1,t }' file1.csv > file2.csv 
    
  2. The computed date-time string has to be updated per line:

    awk '{ print $1,strftime("%r") }' file1.csv > file2.csv
    
kvantour
  • 25,269
  • 4
  • 47
  • 72
  • Works great. TYVM. – ZakS Oct 17 '18 at 12:54
  • I should probably post a new question for this, but how would I set up the code so that what is sent into the CSV is two seperate fields, i.e one column for the $1 and another column for the time? – ZakS Oct 17 '18 at 13:02
  • a space is fine as the FS. In case it is relevant, only file 2 is CSV, file1 is not. – ZakS Oct 17 '18 at 13:04
  • unfortunately this still results in the CSV file putting both fields in one cell, creating 1 column only. – ZakS Oct 17 '18 at 13:14
  • 1
    I have done this, here: https://stackoverflow.com/questions/52856676/awk-outputs-two-fields-into-a-csv-file-but-csv-file-places-both-fields-in-the-s – ZakS Oct 17 '18 at 13:57