burntt999
burntt999

Reputation: 13

replace string in text file with random characters

So what i'm trying to do is this: I've been using keybr.com to sharpen my typing skills and on this site you can "provide your own custom text." Now i've been taking chapters out of books to type so its a little more interesting than just typing groups of letters. Now I want to also insert numbers into the text. Specifically, between each word have something like "393" and random sets smaller and larger than that example.

so i have saved a chapter of a book into a file in my home folder. Now i just need a command to search for spaces and input a group of numbers and add a space so a sentence would look like this: The 293 dog 328 is 102 black. 334 The... etc.

I have looked up linux commands through search engines and i've found out how to replace strings in text files with:

sed -i 's/original/new/g' file.txt

and how to generate random numbers with:

$ shuf -i MIN-MAX -n COUNT

i just can not figure out how to output a one line command that will have random numbers between each word. I'm still-a-searching so thanks to anyone that takes the time to read my problem.

Upvotes: 1

Views: 2548

Answers (2)

dawg
dawg

Reputation: 103884

Given:

$ echo "$txt" 
Here is some random words. Please 
insert a number a space between each one.

Here is a simple awk to do that:

$ echo "$txt" | awk '{for (i=1;i<=NF;i++) printf "%s %d ", $i, rand()*100; print ""}'
Here 92 is 59 some 30 random 57 words. 74 Please 78 
insert 43 a 33 number 77 a 10 space 78 between 83 each 76 one. 49 

And here is roughly the same thing in pure Bash:

while read -r line; do
    for word in $line; do
        printf "%s %s" "$word $((1+$RANDOM % 100))"
    done
    echo
done < <(echo "$txt")   

Upvotes: 0

choroba
choroba

Reputation: 241928

Perl to the rescue!

perl -pe 's/ /" " . (100 + int rand 900) .  " "/ge' < input.txt > output.txt
  • -p reads the input line by line, after reading a line, it runs the code and prints the line to the output
  • s/// is similar to the substitution you know from sed
  • /g means global, i.e. it substitutes as many times as possible
  • /e means the replacement part is a code to run. In this case, the code generates a random number (100-999).

Upvotes: 3

Related Questions