code test
line code test3
asdfasdf
do for while
line1:
code test
line code test3
asdfasdf
do for while
line2:
code test
line code test3
asdfasdf
do for while
I would like to generate 3 main.txt files with the line1 and line2 replaced with corresponding lines from path1 and path2 files.
example
main_1.txt
code test
line code test3
asdfasdf
do for while
datapath1
code test
line code test3
asdfasdf
do for while
pathdata1
code test
line code test3
asdfasdf
do for while
#!/bin/bash
FILE=main.txt
cp $FILE $FILE.bkup.$$
declare -a ar_PATH=($(<paths.txt))
declare -a ar_LINE=($(grep "line.:" "$FILE"))
C=0
for LINE in "${ar_LINE[@]}"
do
sed s,"$LINE","dir$C=${ar_PATH[$C]}",g -i "$FILE" > "${FILE/\.txt/$C}.txt"
((C++))
done
EDIT: Bold stuff has been added after the example, to match the each new filename.
Red part has been removed, to accomplish above said.
If I understood correctly what you specified in post #1 in this thread, you might might also want to try something more like:
awk '
FNR == 1 {
# Note start of an input file...
f++
}
{ # Count the number of lines in each input file and gather text.
l[f, ++lc[f]] = $0
next
}
END { # Verify that the 2nd and 3rd files are not empty and contain the same
# number of lines.
if(lc[2] != lc[3] || lc[2] == 0) {
print "2nd and 3rd files must contain the same # of lines > 0"
exit 1
}
# Create one output file for each line in the 2nd and 3rd files.
for(i = 1; i <= lc[2]; i++) {
# Create the output file name.
fn = "main_" i ".txt"
# Copy lines from the appropriate input file to the output file.
for(j = 1; j <= lc[1]; j++)
print (l[1, j] ~ /^line1:/ ? l[2, i] : \
l[1, j] ~ /^line2:/ ? l[3, i] : \
l[1, j]) > fn
# Close the output file.
close(fn)
}
}' main.txt path1 path2
If you want to try this on a Solaris/SunOS system, change awk to /usr/xpg4/bin/awk or nawk .