Adding an extra date column in UNIX file

Hi All,

I have a file with only one column of data (without delimiter). For Ex:

cat temp.txt
22055
21088
93840
30990
50990
50950

I want to insert an additional column with current date as value. So, i have used below command but didn't get the result as excepted. Could onyone over here please help me in writing the current script command. Also i need to get rid of "space" after the comma delimiter.

awk -vd=`date +%Y%m%d` -F"," -OFS="," '{$2=d; print $1,$2}' temp.txt
22055, 20180928
21088, 20180928
93840, 20180928
30990, 20180928
50990, 20180928
50950, 20180928

What is wrong with the result ("didn't get the result as expected)?

$ sed "s/$/,$(date '+%Y%m%d')/" file
22055,20180930
21088,20180930
93840,20180930
30990,20180930
50990,20180930
50950,20180930

Add the -i option to sed, if it's supported in your version, to write the changes directly to the file if the result is as expected.

1 Like

The result you present is not quite reproducible. -OFS="," causes an error, but when corrected like -vOFS="," , it should yield the desired output without space. You could even simplify your code snippet like

awk -vd=`date +%Y%m%d` -F"," -vOFS="," '{print $1, d}'  file
22055,20180930
21088,20180930
93840,20180930
30990,20180930
50990,20180930
50950,20180930
1 Like

Thanks both of you for your response and showing the error in the command which I return.

  1. I clarified with sed command.
  2. For the output with AWK command what is the difference between OFS and vOFS (should we need to use when we pass a variable to the awk script)?

Could you please let me know.

Thanks & regards,
Suresh G

-v declares a variable to use inside awk. You could also put that at the end, without -v. e.g.

awk -vd=`date +%Y%m%d` -F"," '{print $1, d}' OFS="," file

For 2.: Your phrasing doesn't target the right question. We're dealing with two things:

a) the -v option to awk , which you correctly deploy for the passing of the d variable. man awk :

b) the redefinition of the OFS variable. This can be done in many ways, amongst which

  • -vOFS="<chars?>" in front of the script.
  • OFS="<chars?>" trailing the script
  • BEGIN {OFS="<chars?>"...} (or any other place) within the script