LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Replacing text in a specific field (https://www.linuxquestions.org/questions/programming-9/replacing-text-in-a-specific-field-311839/)

Seventh_Warrior 04-10-2005 08:21 PM

Replacing text in a specific field
 
I'm trying to write a bash script that will find a user in the password file and replace the text in the comment field with something I type in. I've got the finding the user part, but I'm not sure how I would go about replacing the text in the field.

Any ideas?

Tinkster 04-10-2005 08:47 PM

Do you want to see what you're going to replace,
or just slap something over it in the first place?

And which tools do you want to use, what have
you done so far?


Cheers,
Tink

Seventh_Warrior 04-10-2005 09:02 PM

So far I've used grep to find the line in the passwd file containing the username, and awk to display the fifth field.
I've asked the user for input, now I just have to write it to the file.

Tinkster 04-10-2005 09:20 PM

I'd suggest building the entire line in the shell-script,
remove the matching line in place using sed, and then
adding the new line at the end using an
echo $NEW_LINE >> /etc/passwd ...

It's probably possible to do it in place with sed but
the interaction of extracting the user-variable, sed and
eval may turn out to be quite ugly and hard to read :)


Cheers,
Tink

Seventh_Warrior 04-10-2005 09:22 PM

I'll give it a shot, thanks.

sirclif 04-11-2005 12:04 PM

i think gawk would be the tool to use for this, it was created for manipulating fields. gawk could match the first field witht he user name, and then replace field 5 with your comment.

#! /bin/bash
gawk -F ":" -v OFS=":" '$1 != USR {print $0}; $1 == USR {print $1,$2,$3,$4,COMMENT,$6,$7};' USR=$1 COMMENT=$2 $3

say this script is called comment_replace

>comment_replace user_name new_comment /etc/passwd

would print out the new passwd file to stdout, that way you can check to make sure it looks right, then run the same command but redirect the output to a tmp file and then replace /etc/passwd

>comment_replace user_name new_comment /etc/passwd > tmp
>mv tmp /etc/passwd


All times are GMT -5. The time now is 11:56 PM.