Brian Duffy
Brian Duffy

Reputation: 162

Using a variable in awk command to name file

I am splitting up a file with awk command, I want to name the file using a variable however I have not had much luck. Here is the line:

awk '/STX/ {f="$tp"++i;} {print > f}' $tp.mixed

this just creates files with $tp# as name.

I read the post "How to use shell variables in awk script" but was unable to figure out how to apply that to me question.

Upvotes: 1

Views: 462

Answers (2)

anubhava
anubhava

Reputation: 784968

You can use this awk command to pass variable from command line:

awk -v tp="$tp" '/STX/{close(f); f=tp (++i)} f{print > f} END{close(f)}' "$tp.mixed"

Also important is to close the files you're opening for writing output. By calling close we are avoiding memory leak due to large number of opened files.

Upvotes: 3

Brian Duffy
Brian Duffy

Reputation: 162

anubhava answered my question in the comments:

awk -v tp="$tp" '/STX/ {if (f) close(f); f = tp (++i)} {print > f} END{if (f) close(f)}' $tp.mixed

works

thank you everyone for your help

Upvotes: 0

Related Questions