Replacing a template in a text file with a random value

I have a text file with this template:

\t (hello world)

I need to replace the text in brackets with a unique value (e.g. ob1, obj2, etc.), so that

\t (obj)
\t (obj)
\t (obj)

becomes ...

\t (obj1)
\t (obj2)
\t (obj3)

Or something else unique. A solution using any tool running in cygwin will work. My attempt with bash and sed failed to complete this:

#!/bin/bash
x=1
for fl in myfile; do
    cp $fl $fl.old
    sed 's/\\t \(.*\)/\\t \("${x}"\)/g' $fl.old > $fl.new
    x=$((x+1))
    echo $x
done
+3
source share
3 answers

The best way I know how to do this is with perl in-place editing:

eg. myfile.txt contains:

\t (obj)
\t (obj)
\t (obj)

Run in-place editing:

perl -i.bak -ne '$a=int(rand()*2000); s/\((.*?)\)/{$1$a}/g; print' myfile.txt

myfile.txt now contains:

\t (obj1869)
\t (obj665)
\t (obj1459)

Obviously customize 2000to your requirements.

EDIT . If you want to use incremental identifiers, use:

perl -i.bak -ne '$a++; s/\((.*?)\)/{$1$a}/g; print' myfile.txt
+3
perl -pe 's/(?<=[(])[^)]*/"obj" . ++$count/eg'
0

... sed .

sed -r -e "s/\t \((.*)\)/\t \1${x}/g"

However, I'm not sure if they want to your question objgo to obj1, obj2... in the same file, or if each file will get its own unique obj1, obj2...

EDIT Obviously, you need to read the file line by line ... something like this might work.

x=1
while read line; do echo ${line} |  sed -r -e "s/\t \((.*)\)/\t \1${x}/g"; let "x=x+1"; done < myfile.txt > myfile.new.txt

of course easier to use perlas others did

0
source

All Articles