How to pass strings from a list of strings from another file and create multiple files?

Hello Everyone ,

Iam a newbie to shell programming and iam reaching out if anyone can help in this :-

I have two files
1) Insert.txt
2) partition_list.txt

insert.txt looks like this :-

insert into emp1 partition (partition_name) 
(a1,
b2,
c4,
s6,
d8)
select 
a1,
b2,
c4,
s6,
d8
from emp partition (partition_name);
commit;

partition_list.txt looks like this :-

aemp_sec_01P2011_1
yemp_sec_01P2011_4
aemp_sec_01P2011_3
aemp_sec_01P2011_8
aemp_sec_01P2011_10
aemp_sec_01P2012_14
aemp_sec_01P2014_39
aemp_sec_01P2016_10

Each string in the partition_list.txt should replace both the "partition_name" string in the insert.txt file and create a new file for each string used in the partition_list.txt . How can this be achieved without opening the files and modifying . how can it be done through sed or awk ?

For ex :- The end o/p would be 8 new files. sample file will be :-

cat insert_aemp_sec_01P2011_1.txt
insert into emp1 partition (aemp_sec_01P2011_1) 
(a1,
b2,
c4,
s6,
d8)
select 
a1,
b2,
c4,
s6,
d8
from emp partition (aemp_sec_01P2011_1);
commit;
cat insert_yemp_sec_01P2011_4.txt
insert into emp1 partition (yemp_sec_01P2011_4) 
(a1,
b2,
c4,
s6,
d8)
select 
a1,
b2,
c4,
s6,
d8
from emp partition (yemp_sec_01P2011_4);
commit;

so there should be 8 like to be generated based on each line in partition_list.txt.

Iam sorry if i havent used to code tag button ...i apologise .

Hi nubie2linux,
Welcome to the UNIX & Linux Forums.

Your use of CODE tags is fine (and appreciated).

You haven't said what operating system (although we might guess that it is some Linux distribution from your choice of user name) or shell you're using... With a POSIX conforming shell (such as ksh [which is used in the examples below] or bash ) and sed utility you could use something like:

#!/bin/ksh
while IFR= read -r part
do	sed "s/partition_name/$part/" insert.txt  > "insert_$part.txt"
done < partition_list.txt

Or, more efficiently, but requiring a little more typing, with awk :

#!/bin/ksh
awk '
FNR == NR {
	template = template RS $0
	next
}
{	out = substr(template, 2)
	file = "insert_" $0 ".txt"
	gsub(/partition_name/, $0, out)
	print out > file
	close(file)
}' insert.txt partition_list.txt

If you want to use awk on a Solaris/SunOS system, change awk to /usr/xpg4/bin/awk or nawk .

1 Like

Hi Don , Thank you very much for your help . The scripts helped me a lot .
we use linux os and the scripts worked . Thank you again