Borja León
Borja León

Reputation: 11

Create a random name for the complete script

I have a script that joins several csv files into an output file called merged_t*.csv

Here is the script:

for i in $(ls -latr sample_*.csv); 
do  
    paste -d, $i >> out_$RANDOM.csv;
done

sed 's/^|$/\x27/g' out_$RANDOM.csv | paste -d, > merged_t$RANDOM.csv

The "$RANDOM" in the first command "out_$RANDOM" must be the same that the "out_$RANDOM" in the second.

How can i do it?

Upvotes: 0

Views: 644

Answers (3)

Chem-man17
Chem-man17

Reputation: 1770

Ipor Sircer already answered you correctly. The solution is to save the value of $RANDOM into a variable.

To explain why your question had a bug-

Each time you call $RANDOM, it does exactly what it is supposed to- generate a random number. So if you call it multiple times, it will generate different random numbers. So each calling of it will result in a different name. However when you call it once and save it in a variable, it can no longer change (since it has only been called the one time).

$RANDOM is not the best way to generate random numbers though. To test this, you can do the following-

for j in {1..500} 
do 
    for i in {1..1000} 
    do 
        echo "$RANDOM"
   done | awk '{a+=$1} END {print a/NR}' 
done 

What this small script does is generate a thousand $RANDOM outputs (inner loop) and then take the average of the 1000 numbers. It does this 500 times in this example (outer loop). You will see that the averages over any thousand iterations of $RANDOM are quite similar to each other (all around 16000). This shows that there isn't very good variation being observed in the different times you call it.

Better ways include the awk srand command.

Upvotes: 0

m47730
m47730

Reputation: 2261

use the command that already solve your problem: mktemp

csv=$(mktemp out_XXXXXXXXXX.csv) 
for i in $(ls -latr sample_*.csv); 
do  
    paste -d, $i >> ${csv};
done

sed 's/^|$/\x27/g' ${csv} | paste -d, > merged_t${csv}

Upvotes: 1

Ipor Sircer
Ipor Sircer

Reputation: 3141

declare your own variable first:

myrandom=$RANDOM
for i in $(ls -latr sample_*.csv); do
    paste -d, $i >> out_${myrandom}.csv;
done
sed 's/^|$/\x27/g' out_${myrandom}.csv | paste -d, > merged_t${myrandom}.csv

Upvotes: 1

Related Questions