How can I add random string for each line?

Don't you think its bit obvious? You are just generating random string once and storing it in ran variable and using it for all the lines!

Using getline into a variable from a pipe

awk '{
     str_generator = "tr -dc '[:alnum:]' </dev/urandom | head -c 6"
     str_generator | getline random_str
     close(str_generator)
     print "name " random_str " - " $0
}' file

When you use command | getline var, the output of command is sent through a pipe to getline() and into the variable var.

Also note when a pipe is opened for output, awk remembers the command associated with it, and subsequent writes to the command are appended to the previous writes. We need to make an explicit close() call of the command to prevent that.

If the nested single-quotes in the str_generator are causing a problem, replace with its octal equivalent(\047)

awk '{
     str_generator = "tr -dc \047[:alnum:]\047 </dev/urandom | head -c 6"
     str_generator | getline random_str
     close(str_generator)
     print "name " random_str " - " $0
}' file

With awk system() function:

Sample input.txt:

a
b
c

awk '{ 
         printf "name";
         system("tr -dc \047[:alnum:]\047 </dev/urandom | head -c6");
         printf "-%s\n", $0
     }' input.txt

Sample output:

nameSDbQ7T-a
nameAliHY0-b
nameDUGP2S-c

system(command)
Execute the operating system command command and then return to the awk program

https://www.gnu.org/software/gawk/manual/gawk.html#index-system_0028_0029-function


Running one instance of tr -dc '[:alnum:]' </dev/urandom | head -c 6 per line of input would be counter-productive, you'd be better of doing:

<input awk -v rng="LC_ALL=C tr -dc '[:alnum:]' </dev/urandom | fold -w 6" '
  {rng | getline r; print "name"r"-"$0}'

If your input doesn't contain backticks nor single quotes, you could also use m4's mkstemp():

<input sed "s/.*/mkstemp(name)\`&'/" | m4

Tags:

Awk