user1005101
user1005101

Reputation: 95

how to generate random number with find and sed?

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' {} \;

Upvotes: 3

Views: 2085

Answers (2)

Aquarius Power
Aquarius Power

Reputation: 3985

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!

Upvotes: 2

Philippe
Philippe

Reputation: 9752

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.)

Upvotes: 1

Related Questions