-1

How can I update the shell script where I can replace username "u1" to any value from user input in a .txt file

'username' => "u1"

Below is the existing code:-

#!bin/bash
echo "\nEnter Username to replace: "
read name

sed -i -e s/u1/"$name"/g /var/1.txt
Inian
  • 80,270
  • 14
  • 142
  • 161

2 Answers2

0

Try '$name' instead of "$name"

Best option is to use sed -i -r

 sed -i -r 's/u1/'$name'/g'  /var/1.txt

Another option you can try is save this to temp file and move it back

Example :

 sed 's/u1/'$name'/g' /var/1.txt > /tmp/temp

 mv /tmp/temp /var/1.txt
sterin jacob
  • 141
  • 1
  • 10
  • The option with -r worked great! many thanks. in next iteration, I pass on input "u3" to be replaced by "u2" (from previous execution of above code, value "u2" is replaced by "u1"). how can this be handled? – deepak rao Aug 01 '16 at 11:55
  • I didn't understand your requirement completely . put sed in the loop . Also Please upvote my answer , if you got the answer you looking for – sterin jacob Aug 01 '16 at 12:06
  • I want to replace "u1" or any other value from input Example:- 'username' => "u1" Input value -> u2 o/p:- 'username' => "u2" code re-execution:- 'username' => "u2" Input value -> u3 o/p results:- 'username' => "u3" – deepak rao Aug 01 '16 at 12:39
  • can you put the sample content of /var/1.txt? – sterin jacob Aug 01 '16 at 13:03
  • Never do `'s/x/'$y'/'` as that leaves `$y` unquoted and so open to shell interpretation. Also never do `cmd file > tmp; mv tmp file` as that will zap your original file if/when `cmd` files. The `-r` is adding no value. The safer way to write the above is `sed -i 's/u1/'"$name"'/g' /var/1.txt` or `sed 's/u1/'"$name"'/g' /var/1.txt > /tmp/temp && mv /tmp/temp /var/1.txt` and be aware it will still fail if `$name` contains capture group reference (e.g. `&` or `\1`) or regexp delimiter (e.g. `/`) or some other characters. See http://stackoverflow.com/q/29613304/1745001. – Ed Morton Aug 01 '16 at 17:44
0

Using sed, we can split a statement into two - and replace the second part with the required variable [here, $name] - instead of hardcoding the script with u1.

sed -i "s#\(.*'username' =>\)\( .*\)#\1 "\"$name\""#" /var/1.txt

The same result can be achieved using awk as below:

awk -v name="$name" '/username/{gsub($3,"\""name"\"")};1' /var/1.txt

sca
  • 39
  • 2
  • and if I need to add a comma at the end of $name, how can I handle this? Example:- $name= admin output:- admin, – deepak rao Aug 26 '16 at 13:14