Replace 2nd column for each line in a csv file with fixed string+random number

Hi experts,

My csv file looks like this

U;cake;michael;temp;;;;
U;bread;john;temp;;;;
U;cocktails;sarah;temp;;;;

I'd like to change the value fo 2nd column to cf+random number , which will look maybe something like this

U;cf20187;michael;temp;;;;
U;cf8926;john;temp;;;;
U;cf1009;sarah;temp;;;;

Also it may consists more than 3 lines.
:wall:please help thanks!

awk -F\; 'BEGIN {srand()} {sub ($2,"cf"int(rand()*100000)); print}' infile.csv

where 100000 is whatever maximum value you want.

If you want the same sequence every time just remove the srand() section:

awk -F\; '{sub ($2,"cf"int(rand()*100000)); print}' infile.csv
awk -F';' '
function randint(n) {
  return int(n * rand())
}
BEGIN {          
  OFS=";"
  srand()                     
}                           
{ $2 = "cf" randint(65535) }1          
' INPUTFILE
U;cf31289;michael;temp;;;;
U;cf26763;john;temp;;;;
U;cf50994;sarah;temp;;;;

Dear carloM and yazu,

Thank you for your replies. However I am getting syntax error and bailing out on line 1 for carloM and syntax error and bailing out on line 2 for yazu. I wonder whats wrong :frowning:

If Solaris, use nawk

--ahamed

Thank you everyone!. it worked nicely! :slight_smile:

---------- Post updated at 10:47 PM ---------- Previous update was at 08:32 PM ----------

Dear all,

Let say I just want to alter the first row for the second column to a value called, 'type' instead of cf+random numbers.

so basically does the same thing, except, only for the first row, and change the value to 'type', instead of cf10923 for example. How do I this?

'type' is literal text? Do you only want the first row, or the whole file?

Assuming it is and you want the whole thing:

nawk -F\; 'NR == 1 {sub ($2,"type"); print} NR > 1 {print}' infile.csv

or if you only want row 1:

nawk -F\; 'NR == 1 {sub ($2,"type"); print}' infile.csv

this will work on any system:

perl -pe "s/^U;.+?;/'U;cf'.(int rand(99999)+0).';'/e" file.in > file.out

(99999)+0 - means random number from 0 to 99999