1

I need to make an interactive bash script where the user will input a word, for example 'xyz' and it will replace a word in a text file.

For example, I have a script called example.sh. When i run it, it should ask:

What is your name?: 
and the user will input 'xyz'.

The script should take that input and replace 'username' inside a text file called userlist.txt to 'xyz'

to be more clear, I need user input to run

sed -i -e s/username/userinput/g userlist.txt

1
  • Do you have any code that you've tried so far? Can you add it to your post? Commented May 26, 2013 at 22:02

2 Answers 2

3

You can use the read builtin to read user input, and you can then use sed(1) to do the text replacement:

if read -p "What is your name? " name; then
  sed -i~ -e "s/username/${name}/g" userlist.txt
else
  # Error
fi
Sign up to request clarification or add additional context in comments.

3 Comments

I can't make this work, the username just gets replaced by ${name}, on Arch Linux
EDIT: The name has "/" in it. like /dev/sda. So I get error "unknown option to 'd', unknown option to 's'"
@user156238: The problem is, you aren't passing $name to sed like an argument: you are dynamically constructing a command using the value of $name, and so any characters in the variable that have special meaning to sed are treated as such. You'll need to preprocess the value of $name before using it with sed to quote such special characters: a non-trivial task.
1
#!/bin/bash
echo "What is your name?"
read name
sed -i -e s/username/"$name"/g userlist.txt

2 Comments

I can't make this work, the username just gets replaced by "$name", on Arch Linux
@user156238 Weird, worked for me on Linux Slackware. And Adam Rosenfields answer worked too - I tested them both.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.