0

I have a below awk command which is looking into "test.sql" file (which has multiple CREATE TABLE statements), I want to generate multiple files based on each CREATE TABLE statement. For which I could achieve with the below command.

But the current file names that are generated is as below : F1.sql F2.sql ...

awk  '/CREATE TABLE/{x="F"++i".sql";}{print > x;}' test.sql

So instead of giving F1.sql or F2.sql, I want to substitute the varaible "F" with some shell holding variable.

Current OutPut is: F1.sql F2.sql

Expected Output: Declred variable F="test"

Output: test1.sql test2.sql

Please suggest.

Sampat Kumar
  • 492
  • 1
  • 6
  • 14

1 Answers1

1

You are just incorrectly using the awk variable that you imported from the shell. It cannot be within quotes, under which it is interpreted as a literal string.

F="test"
awk -v fname="$F" '/CREATE TABLE/{x=fname""++i".sql";}{print > x;}' test.sql

Also you could close the file descriptors opened as part of print > x with an explicit close() call i.e. as

awk -v fname="$F" '/CREATE TABLE/{x=fname""++i".sql";}{print > x; close(x)}' test.sql
Inian
  • 80,270
  • 14
  • 142
  • 161