Friday, 7 August 2009

command line loop: copy file with incrementing filename and substitute text

for example:

Test the command:
for i in 0 1 2 3 4 5 6 7; do echo cp tol_b3.DAT tol_b1$i.DAT; done

Run the command:
for i in 0 1 2 3 4 5 6 7; do cp tol_b3.DAT tol_b1$i.DAT; done



Substitute parameter: This uses sed, with all the files.

To replace 'abc' with def' in file, 'xyz':

sed -e 's/abc/def/' xyz > xyz


So, to replace ''step' = 1' with ''step' = index' where index is increasing:
(note, the tmp and mv is required, as sed will wipe the file, otherwise.)


for i in 0 1 2 3 4 5 6 7;
do
sed -e "s/step' = 1/step' = $i/" tol_b1$i.DAT > tmp
mv tmp tol_b1$i.DAT
done

which becomes the following one line:

for i in 0 1 2 3 4 5 6 7; do sed -e "s/step' = 1/step' = $i/" tol_b1$i.DAT > tmp; mv tmp tol_b1$i.DAT; done


Also, sets of files being copied / renamed (according to Gavin):

for s in Writings.*; do mv $s ${s/'Writings'/'Index'}; done;

No comments:

Post a Comment