Reputation: 177
I want to substitute a String from a file which is:
# - "server1"
My first attempt was something like this:
sed -i 's/#\ -\ "\server1"\.*/ChangedWord/g' file
But I get an error if I try it like this.
So there is to be another way to handle whitespaces, I guess I have to use \s or [[:space:]]. But for some how I am not able to make it work.
Upvotes: 0
Views: 4420
Reputation: 177
The actual fault was the missing escaping from the double quotes:
ssh -i file root@IP sed 's/^#[[:space:]]*-[[:space:]]*\"server1\".*/ChangedWord/' file
That did it for me. Thanks for all your support
Upvotes: 1
Reputation: 289855
I think you are complicating the expression too much. This should be enough:
sed 's/^#[[:space:]]*-[[:space:]]*"server1".*/ChangedWord/' file
It looks for those lines starting with #
followed by 0 to n spaces, then "server1"
and then anything. In such case, it replaces the line with ChangedWord
.
Note I am using [[:space:]]
to match the spaces, since it is a more compatible way (thanks Tom Fenech in comments).
Note also there is no need to use g
in the sed
expression, because the pattern can occur just once per line.
$ cat a
hello
# - "server1"
hello# - "server1"
$ sed 's/^#[[:space:]]*-[[:space:]]*"server1".*/ChangedWord/' a
hello
ChangedWord
hello# - "server1"
Upvotes: 5
Reputation: 293
rghome is right, you don't need those backslashes in front of spaces as the expression is wrapped in quotes. In fact, they're causing the error: sed
is telling you that \<Space>
is not a valid option. Just remove them and it should work as expected:
sed -i 's/# - "server1"/ChangedWord/' file
Upvotes: 0