0

I have a csv file that I need to add a number of columns at the end. The new columns are variables taken from other files.

STNO=3389
STNNAME=SWORDS

awk -F "," '{ stnname='"$STNNAME"';stno='"$STNO"';print $0","stnname","stno }' infile

example of the output.

992501062,-6.278983000,202105210736,,3389

The stno is written fine but the stnname is blank. It seems like I can use numeric variables but not text.

any help appreciated. thanks.

demailyea
  • 15
  • 4
  • Thanks for showing your efforts, sorry but this is not clear, could you please explain it more what you are trying to achieve here, thank you(not my downvote btw). – RavinderSingh13 May 28 '21 at 10:44
  • @RavinderSingh13 apologies I wasn't clear enough, I'm newish to this and was trying to be as concise as possible. Tks for the reply – demailyea May 28 '21 at 12:38
  • 2
    I suspect there's a better approach that involves just running awk on your CSV and the files you''re populating those variables from rather than extracting their values in shell first. – Ed Morton May 28 '21 at 13:25

2 Answers2

5

You are interpolating the literal symbol SWORDS where apparently you were hoping to interpolate a quoted string. Awk has no variable named SWORDS so it resolves to an empty string.

Better hygiene and stability altogether is to avoid interpolating junk right into your Awk script. Use -v on the Awk command line to pass in values.

awk -v stnname="$STNNAME" -v stno="$STNO" 'BEGIN {FS=OFS=","}
{ print $0, stnname , stno }' infile

Tangentially, avoid upper case for your private shell variables.

tripleee
  • 175,061
  • 34
  • 275
  • 318
2

It is very easy to get lost in a sea of quotes. Maybe catch the env variables using -v like this:

awk -v stnname="$STNNAME" -v stno="$STNO" -F "," '{ print $0,stnname,stno }' infile

then you can use them in the command directly without trying to piece together a string

doctorlove
  • 18,872
  • 2
  • 46
  • 62