-3

I have a string having the following format:

ip = 192.168.1.2
user = test
password = test0

ip =, user = and password = are fixed but the strings to the right of the equals signs may vary.

Using Perl, I would like to write a one-line command to replace the string following user = with a given string, say, X, to return the following new string:

ip = 192.168.1.2
user = X
password = test0

Thanks for your help.

Arkadiusz Drabczyk
  • 11,227
  • 2
  • 25
  • 38
KLA
  • 31
  • 1
  • 8
  • I trust I kept your meaning with my edit, but it's your question, so feel free to rollback to your original question or edit my edit. In particular, you may wish to refer to a file rather than a string. I made it a string to simplify your question as I thought you were mainly concerned about string manipulation. – Cary Swoveland Mar 15 '20 at 21:50

1 Answers1

2
$ perl -p -e 's/^user =.*/user = X/' file
ip = 192.168.1.2
user = X
password = test0

If you want the string to substitute to be configurable, you can use the following:

$ user=X
$ perl -spe's/^user =\K.*/ $user/' -- -user="$user" file
ip = 192.168.1.2
user = X
password = test0

See Specifying file to process to Perl one-liner.

ikegami
  • 367,544
  • 15
  • 269
  • 518
Arkadiusz Drabczyk
  • 11,227
  • 2
  • 25
  • 38