3

how to generate random number in this code? I try use $RANDOM, but the number is still the same. How to improve it?

find . -type f  -exec sed -i 's/<field name=\"test/<field name=\"test$RANDOM/g' {} \;

2 Answers2

2

you can also avoid creating a script file with this "one line" way, ex.:

function FUNCtst() { echo "tst:$1";echo "tst2:$1"; }; export -f FUNCtst; find -exec bash -c 'FUNCtst {}' \;

so, you:

  1. create a complex function
  2. export -f the funcion
  3. find executing bash, that calls the exported funcion

and, no need to create a file!

Aquarius Power
  • 3,729
  • 5
  • 32
  • 67
1

That happens because the $RANDOM function invocation is substituted with its result when you run the find command, not when find runs the sed command.

What you can do is put the sed -i ... part in a script, and pass this script to find instead.

For instance, if subst.sh contains:

#!/bin/bash
r=$RANDOM
sed -i "s/<field name=\"test/<field name=\"test${r}/g" $@

Then

find . -type f -exec ./subst.sh {} \;

should do the trick, because $RANDOM is going to be evaluated as many times as there are files.

(Note that the random number will still be the same across one particular file, but it will be distinct for different files.)

Philippe
  • 9,582
  • 4
  • 39
  • 59
  • It works! Thanks! Sorry, I'm new in bash, what does it mean $@ ? – user1005101 Oct 20 '11 at 12:04
  • It's the array of all command-line arguments to the script. In this case, passing the first argument would have sufficed, so you could also have written $1. – Philippe Oct 20 '11 at 12:05