1

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.

9
  • 2
    Possible duplicate of How to use shell variables in awk script Commented Oct 15, 2015 at 19:19
  • 4
    You don't expand the shell variable in the awk script. You use -v awkvar="$tp"`` to create an awk variable with the value you need and then use the variable awkvar` in the awk script. f=awkvar(++i) or similar. Commented Oct 15, 2015 at 19:23
  • 1
    awk -v tp="$tp" '/STX/ {if (f) close(f); f = tp (++i)} {print > f} END{if (f) close(f)}' $tp.mixed Commented Oct 15, 2015 at 19:40
  • 1
    Thank you anubhava!! that worked. Question, why do you have to have the if (f) close (f) and END{if (f) close(f)? thank you, trying to understand shell scripting and awk better. Commented Oct 15, 2015 at 19:44
  • 2
    @BrianDuffy There is a limit on the number of open files you can have. If you explicitly use close every time you are done with a file here, you will never reach that limit. Commented Oct 15, 2015 at 19:50

2 Answers 2

3

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.

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.