apple
apple

Reputation: 127

replace a line with bash script

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!

Upvotes: 0

Views: 127

Answers (2)

Barmar
Barmar

Reputation: 780698

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

Escaping the space will keep it from being trimmed.

Upvotes: 1

j883376
j883376

Reputation: 1135

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.

Upvotes: 0

Related Questions