2

I'm trying to build a simple script which randomises data. I will make it very simple.

Let's say I have the following data inside data.txt: 11 222 333 4444 55555

So basically some numbers delimited by a space. What I want is to add letters from a to h after each digit. Randomly selected from an array or from a file.

The problem is after executing the script, I get the same variable value after each letter.

Expected result: 1a1b 2f2a2e 3e3b3d 4a4g4h4c 5a5d5f5a5c

What I get is: 1g1g g2g2g2g g3g3g3g g4g4g4g4g g5g5g5g5g5

Script looks like this:

#!/bin/bash
letters=("a" "b" "c" "d" "e" "f" "g" "h")
random=$(shuf -i 1-9999 -n 1)
result=${letters[$random % ${#letters[@]}]}
result2=$(awk '$1=$1' FS= OFS="$result" $1)
echo $result2;
mikerssen
  • 21
  • 1
  • You need to loop around and generate a new random digit each time. You are basically asking awk to print alternate characters separated by the single random letter you determined in the 3rd line. – cbz May 07 '19 at 15:21
  • I need to generate letters and insert them after each digit. Unfortunately, I don't know how to do the loop. I'll read a bit – mikerssen May 07 '19 at 15:28
  • If you have `gawk` (check with `awk --version`), then write the whole thing in `awk`, it will be much more efficient. See https://www.gnu.org/software/gawk/manual/gawk.html#Cliff-Random-Function for how to generate random numbers inside your script. AND, ++ for good (enough) first Q ;-) Good luck. – shellter May 07 '19 at 15:33
  • Oh yeah, and you need to use the `%` (modulo) operator to key into your list of chars that should be randomized. (As you seem to understand in your current code). – shellter May 07 '19 at 15:35
  • 1
    See [chepner's answer](https://stackoverflow.com/a/10552175/4154375) to [How to perform a for loop on each character in a string in Bash?](https://stackoverflow.com/q/10551981/4154375). (It's by far the most upvoted answer. Ignore the (poor) accepted answer.) Bash has a built-in random number generator (`$RANDOM`), so you don't need to use an external tool (such as `shuf`). See [Select a random item from an array](https://stackoverflow.com/q/2388488/4154375) to learn how to select a random letter from the `letters` array. (The accepted, and most upvoted, answer is good.) – pjh May 07 '19 at 17:51
  • Didn't figure it out yet. I'm spending a lot of time for this script but I think this it's the beginner price. I hope I will get done this soon. Thanks guys. I can't accept an answer yet as I don't know how to implement it. – mikerssen May 08 '19 at 01:44
  • Can't figure it out. Is there anybody who is able to do this for me? Thanks.. – mikerssen May 09 '19 at 21:27

0 Answers0