LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   use script to create a data file of mulitple users (https://www.linuxquestions.org/questions/linux-newbie-8/use-script-to-create-a-data-file-of-mulitple-users-602771/)

RajRed 11-27-2007 12:02 PM

use script to create a data file of mulitple users
 
How do I write a script that read a line from a file and recreate mulitple lines in another file? for example, I have one line information about a user, the prefix user name is 'test', user's email address is 'test@abc.xyz.com', the alias is 'test' etc. I want to populate this data into the following,


test1 test1@abc.xyz.com test1
test2 test2@abc.xyz.com test2
test3 test3@abc.xyz.com test3
:
test5000 test5000@abc.xyz.com test5000

In other word, the script needs to read the first token (user name prefix) from the first file and create mulitple users by appending the counts and replace the email address from the first time with the new user name and the alias. The script will accept the command line parameter for the max number of users like

"createuser.sh 5000" will create 5000 users, 1 line per user.

Any help is appreciate.

slakmagik 11-27-2007 01:18 PM

This is either mondo sysadmin stuff or homework. Assuming the former, this is kinda crappy, but
Code:

user="$(awk '{ print $1 }' file)"
>file2
for (( i=1; i<=$1; i++)); do
    sed "s/$user/$user$i/g" file >> file2
done

might do if file contains only a single line in the format you gave. Otherwise, you'd need a way to extract the line from the first file. And this might do that,
Code:

user="$(awk '/'$1'/{ print $1 }' file)"
>file2
for (( i=1; i<=$2; i++)); do
    sed "s/$user/$user$i/g" file >> file2
done

Doesn't work if USER is 'John Doe', though. A 'John Doe5000' doesn't make much sense, though.

I'm sure there's a better way, but that's the first thing that came to mind.

JSkywalker 11-27-2007 01:22 PM

something like:
Code:

#!/bin/bash

for ((x=1; x<=$1; x++)) do
        echo test$x test$x@abc.xyz.com test$x;
done


RajRed 11-27-2007 03:22 PM

thanks, for the code you provided below, where I specify the first file?

user="$(awk '/'$1'/{ print $1 }' file)"
>file2
for (( i=1; i<=$2; i++)); do
sed "s/$user/$user$i/g" file >> file2
done

slakmagik 11-27-2007 06:05 PM

The first $1 is bash expecting the user name you want, like 'test'. The second $1 is awk grabbing the first field. The $2 is the number argument, like '5000'. So it'd be 'createuser.sh test 5000'. I thought the file names were supposed to be 'hard coded'. If you wanted to provide the file names as command line arguments, just substitute 'file' (input) and/or 'file2' (output) with $3 and $4 throughout. 'Course, then you're getting into the ballpark of maybe wanting to use getopts and letter options, rather than trying to remember the order of everything.


All times are GMT -5. The time now is 02:35 PM.