0

I want to insert a different random number at the beginning of every line in a file.

My last attempt looks like:

#!/bin/bash
n=$RANDOM
awk '{sub(/^/, "$n,");print}' file

Also, how do I just change the file, not print to stdout? tnx

  • Do you want to insert a different random number on each line? If so, this isn't a duplicate. Otherwise, it is. – Tom Fenech Jun 09 '15 at 16:09
  • Yes, I want to put a different random number on each line. tnx – user1222303 Jun 09 '15 at 16:50
  • In that case, passing a random number in from bash won't work, since bash is generating only *one* random number, not one per line. You should ask how to generate random numbers in awk instead. – Charles Duffy Jun 09 '15 at 16:59
  • Otherwise, you could just ask how to do this in native bash, without awk involved at all -- that would be an easy one to answer too. – Charles Duffy Jun 09 '15 at 17:00
  • ...that said, asking how to edit files in-place with awk is _also_ its own question, and shouldn't be compounded with anything else. (When you ask multiple questions together, that confounds people's ability to vote up/down answers in terms of how good they are for the question asked, since there no longer _is_ a single question asked; it also breaks our functionality for calling out duplicates, since the chances of people asking the same two questions together are much lower than the chances of multiple people asking the same questions decoupled). – Charles Duffy Jun 09 '15 at 17:00
  • 1
    What range should the random numbers be in? Any POSIX-compliant version of awk has `rand()`, which returns numbers in the interval [0,1) but that's not the same as bash's `$RANDOM` which returns integers between 0 and 2^16-1. – Tom Fenech Jun 09 '15 at 17:08
  • @Charles your points are valid but it's difficult to decouple deciding on an approach (albeit a broken one) and showing an attempt (which we encourage), and the problems you mention, especially to those less familiar with the set of tools we're dealing with here. – Tom Fenech Jun 09 '15 at 17:14
  • @TomFenech, I'm not sure whether and on what we disagree. Showing an attempt is indeed good, whereas specifying an approach (when it inappropriately limits the range of acceptable answers) is bad. – Charles Duffy Jun 09 '15 at 17:44
  • @Charles yeah I guess there's not much difference in our opinions. I'm just wary of coming down too hard on people that have, perhaps accidentally, been a bit prescriptive in their question. – Tom Fenech Jun 09 '15 at 19:56
  • @user1222303 if you answer the questions in our comments, we can reopen your question and provide you with a solution. – Tom Fenech Jun 09 '15 at 22:11

0 Answers0