0

I am trying to replace a line of my file. I used

line=" abc"
sed -i "3c ${line}" test.txt

It works but the first space doesn't show up. I want the line 3 in test.txt to be

 abc

rather than

abc

notice there is a space before abc. thanks for any suggestions!

2 Answers 2

1
line="\ abc"
sed -i "3c\
$line" test.txt

Escaping the space will keep it from being trimmed.

Sign up to request clarification or add additional context in comments.

Comments

0

The syntax of a sed replacement command is 's/match/replacement/'. In order to find abc and replace it, you need to do something like:

line=" abc"
sed -i "s/^abc$/$line/" test.txt

The characters ^ and $ are regular expression meta characters for the beginning and the end of the line, respectively. So ^abc$ will only match lines containing exactly that pattern and then replace it with abc with the space before it.

1 Comment

abc is what he's adding, not something being matched for replacement.

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.