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!
line="\ abc"
sed -i "3c\
$line" test.txt
Escaping the space will keep it from being trimmed.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.