1

I want to delete a string from a file. This string is provided by the user. I tried the following command which didn’t work.

read -r input
sed -i '/"$input"/d' xyz.txt

I tried without double quotes("") as well. But it didn’t work.

Could you guys please help me?

2
  • You said you want to delete a string, but the command you've used deletes the whole line the string is in. This is a different outcome than what you've expressed. Which is desired? Commented Apr 4, 2016 at 12:53
  • in this case the whole line is the string Commented Apr 5, 2016 at 6:27

2 Answers 2

3

You can use:

sed -i "/$input/d" xyz.txt

but make sure input doesn't contain any regex special character.

awk with index function might be safer due to non-regex:

awk -v input="$input" '!index($0, input)' xyz.txt > $$.temp && mv $$.temp xyz.txt
Sign up to request clarification or add additional context in comments.

Comments

1

The problem is that variables won't be expanded when put inside single quotes.

So you need to use double quotes:

sed -i.bak "/$input/ d" xyz.txt

The original file will be kept as xyz.txt.bak and the modified file will be xyz.txt.

If you do not want a backup:

sed -i "/$input/ d" xyz.txt

Comments

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.