Reputation: 609
I have a text file:
example.txt
UserName = JIU62H123;
USER_NAME = JIU62H123;
I need to change JIU62H123
to A5B4C6DF9
. Obviously, for this file I could just do:
//bash
sed -i '' 's/JIU62H123/A5B4C6DF9/g' example.txt
This works for this file as you can see from the result:
example.txt
UserName = A5B4C6DF9;
USER_NAME = A5B4C6DF9;
However, in actuality, I won't know if the username is actually ahead of time. All I know is that the file is in this shape:
example.txt
UserName = <some_letters_and_numbers>;
USER_NAME = <some_letters_and_numbers>;
I basically need to change <some_letters_and_numbers>
to A5B4C6DF9
. Can this be done with one or more sed
commands?
Upvotes: 0
Views: 488
Reputation: 609
thanks very much for the answers, upvoted each one. I ended up doing a solution like so:
sed -i '' -E 's/(DEVELOPMENT_TEAM|DevelopmentTeam)( = )(.*)/\1\2A5B4C6DF9;/' example.txt
Most of the answers given here seemed to be matching for a pattern of letters/numbers, but I think it might be better to match against anything and replace it with the desired content.
Upvotes: 0
Reputation: 70722
UserName
or USER_NAME
, followed by equal sign =
,sed
syntax:Using variable for adaptability
newId=A5B4C6DF9
sed -e '/^U\(serName\|\SER_NAME) *=/s/= .*$/'$newId/ -i example.txt
Nota The quoted part end just before the variable!
This work until $newId
don't contain special chars. If variable could contain spaces or other non alphanumeric characters, use double-quotes:
sed -e '/^U\(serName\|\SER_NAME) *=/s/= .*$/'"$newId"/ -i example.txt
Upvotes: 2
Reputation: 203169
To change <some_letters_and_numbers> to A5B4C6DF9
and assuming you meant to add on the right side of "= "
with a sed that has -E
for EREs is:
$ sed -E 's/= [[:alnum:]]+/= A5B4C6DF9/' file
UserName = A5B4C6DF9;
USER_NAME = A5B4C6DF9;
and with any POSIX sed:
$ sed 's/= [[:alnum:]][[:alnum:]]*/= A5B4C6DF9/' file
UserName = A5B4C6DF9;
USER_NAME = A5B4C6DF9;
Upvotes: 1
Reputation: 37394
With awk you could:
$ awk '{$3="A5B4C6DF9;"}1' file
UserName = A5B4C6DF9;
USER_NAME = A5B4C6DF9;
ie. replace the 3rd space separated field. With a recent enough GNU awk you could do an inplace edit:
$ awk -i inplace '{$3="A5B4C6DF9;"}1' file
Upvotes: 1
Reputation: 560
How about using a regex?
sed -ir 's/^(USER_NAME|UserName) = [A-Za-z0-9]+;$/\1 = A5B4C6DF9;/g' example.txt
Upvotes: 2