简体   繁体   中英

Using sed to replace a part of a string that is unknown

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?

如何使用正则表达式?

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

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

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

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM