Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a string with a random number for every line, in every file, in a directory in Bash

Tags:

bash

shell

sed

awk

!/bin/bash

for file in ~/tdg/*.TXT
  do
    while read p; do
      randvalue=`shuf -i 1-99999 -n 1`
      sed -i -e "s/55555/${randvalue}/" $file
    done < $file
  done

This is my script. I'm attempting to replace 55555 with a different random number every time I find it. This currently works, but it replaces every instance of 55555 with the same random number. I have attempted to replace $file at the end of the sed command with $p but that just blows up.

Really though, even if I get to the point were each instance on the same line all of that same random number, but a new random number is used for each line, then I'll be happy.

EDIT

I should have specified this. I would like to actually save the results of the replace in the file, rather than just printing the results to the console.

EDIT

The final working version of my script after JNevill's fantastic help:

!/bin/bash

for file in ~/tdg/*.TXT
do
  while read p; 
  do
    gawk '{$0=gensub(/55555/, int(rand()*99999), "g", $0)}1' $file > ${file}.new
  done < $file
  mv -f ${file}.new $file
done
like image 883
Simoney Avatar asked Oct 15 '25 23:10

Simoney


1 Answers

Since doing this is in sed gets pretty awful and quickly you may want to switch over to awk to perform this:

awk '{$0=gensub(/55555/, int(rand()*99999), "g", $0)}1' $file

Using this, you can remove the inner loop as this will run across the entire file line-by-line as awk does.

You could just swap out the entire script and feed the wildcard filename to awk directly too:

awk '{$0=gensub(/55555/, int(rand()*99999), "g", $0)}1' ~/tdg/*.TXT
like image 132
JNevill Avatar answered Oct 17 '25 14:10

JNevill