I think it would be a mistake to call so many sed
s where only one will do. sed
's claim to fame is its ability to efficiently loop over input and modify it into different output, but it can handle multiple outputs very easily as well. Here, for example, is a POSIX portable (and far more efficient) rewrite of your for
loop:
echo "Solve[x^2+5^a==$((a=0)),x]>>a.out" >/tmp/i.m ###create file + init $a
until [ "$((a+=1))" -gt 10 ] ###iterate + test
do printf "h;s/a/$a/gpw /tmp/$a.m\ng;" ###push new sed command
done| sed -nf - /tmp/i.m ###read + apply commands
head /tmp/[0-9].m /tmp/10.m ###print results
sed
can read its script from stdin and apply it to a named file - which is what the sed -nf - /tmp/i.m
statement above does. It can also simultaneously p
rint its output to stdout and w
rite its output to one or more named files. As the shell loop works it prints lines at sed
which, when it is finished, amount to:
h;s/a/1/gpw /tmp/1.m
g;h;s/a/2/gpw /tmp/2.m
g;h;s/a/3/gpw /tmp/3.m
g;h;s/a/4/gpw /tmp/4.m
g;h;s/a/5/gpw /tmp/5.m
g;h;s/a/6/gpw /tmp/6.m
g;h;s/a/7/gpw /tmp/7.m
g;h;s/a/8/gpw /tmp/8.m
g;h;s/a/9/gpw /tmp/9.m
g;h;s/a/10/gpw /tmp/10.m
g
Which tells sed
to...
- Overwrite its
h
old buffer with a copy of its edit buffer.
g
lobally s///
ubstitute every occurrence of the letter a
in its edit buffer with whatever the current value for the shell variable $a
.
- While also both
p
rinting the results of that s///
ubstitution to stdout and w
riting the results to the file named /tmp/$a.m
where $a
is an iterable.
- And last to
g
et the hold buffer by overwriting the edit buffer.
sed
will apply this sequence for every line in its named input file. When first called it will truncate each of its named w
rite files, but will thereafter append each w
rite action to each output file in sequence. Because I have only the one line in i.m
, though, sed
prints:
Solve[x^2+5^1==0,x]>>1.out
Solve[x^2+5^2==0,x]>>2.out
Solve[x^2+5^3==0,x]>>3.out
Solve[x^2+5^4==0,x]>>4.out
Solve[x^2+5^5==0,x]>>5.out
Solve[x^2+5^6==0,x]>>6.out
Solve[x^2+5^7==0,x]>>7.out
Solve[x^2+5^8==0,x]>>8.out
Solve[x^2+5^9==0,x]>>9.out
Solve[x^2+5^10==0,x]>>10.out
And head
, reading from each of the newly created ten files in /tmp
, prints:
==> /tmp/1.m <==
Solve[x^2+5^1==0,x]>>1.out
==> /tmp/2.m <==
Solve[x^2+5^2==0,x]>>2.out
==> /tmp/3.m <==
Solve[x^2+5^3==0,x]>>3.out
==> /tmp/4.m <==
Solve[x^2+5^4==0,x]>>4.out
==> /tmp/5.m <==
Solve[x^2+5^5==0,x]>>5.out
==> /tmp/6.m <==
Solve[x^2+5^6==0,x]>>6.out
==> /tmp/7.m <==
Solve[x^2+5^7==0,x]>>7.out
==> /tmp/8.m <==
Solve[x^2+5^8==0,x]>>8.out
==> /tmp/9.m <==
Solve[x^2+5^9==0,x]>>9.out
==> /tmp/10.m <==
Solve[x^2+5^10==0,x]>>10.out
for i in {1..10}; do sed "s/a/$i/" a.m > "$i.m"; done
– Costas Mar 04 '15 at 21:38