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.

3
  • 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). Commented May 28, 2021 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 Commented May 28, 2021 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. Commented May 28, 2021 at 13:25

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

You need to set OFS to a comma too.
True - I focused on the -v bit... your answer has the whole thing

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.