0

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?

Moshe Slavin
  • 5,127
  • 5
  • 23
  • 38
inhwrbp
  • 569
  • 2
  • 4
  • 17

5 Answers5

2

How about using a regex?

sed -ir 's/^(USER_NAME|UserName) = [A-Za-z0-9]+;$/\1 = A5B4C6DF9;/g' example.txt
sdht0
  • 500
  • 4
  • 8
2

In real words:

  • on lines begining by UserName or USER_NAME, followed by equal sign =,
  • replace right hand side by ...

In 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
F. Hauri - Give Up GitHub
  • 64,122
  • 17
  • 116
  • 137
1

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
James Brown
  • 36,089
  • 7
  • 43
  • 59
1

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;
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0

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.

inhwrbp
  • 569
  • 2
  • 4
  • 17