Reputation: 129
Hi I have trouble appending newline by sed command. I was instructed to write a command that update host file. Also, My sed command is written in bash script, though it kept outputting error message. It said "sed: -e expression #1, char 93: extra character after command."
this is the contend I want to add to my hosts file.
# Gateway
10.0.0.1 schoolhost it20
# Addresses for the Windows
10.0.0.240 host1 it21
10.0.0.241 host2 it22
This is the command I wrote in bash script.
sed -i "/hosts/a \
\n# Gateway \
\n10.0.0.1 schoolhost it20 \
\n# Addresses for the Windows PCs \
\n10.0.0.240 host1 it21 \
\n10.0.0.241 host2 it22" hosts
Upvotes: 1
Views: 606
Reputation: 103834
Given:
$ cat file
line 1
line 2
line 3
And:
$ echo "$add_this"
# Gateway
10.0.0.1 schoolhost it20
# Addresses for the Windows
10.0.0.240 host1 it21
10.0.0.241 host2 it22
You can do several things to add those text elements together.
The first is to use cat
(recalling the name comes from concattenate):
$ cat file <(echo "$add_this")
line 1
line 2
line 3
# Gateway
10.0.0.1 schoolhost it20
# Addresses for the Windows
10.0.0.240 host1 it21
10.0.0.241 host2 it22
Or, you can use awk
the same way:
$ awk '1' file <(echo "$add_this")
# same output
Or, an empty sed
:
$ sed -e '' file <(echo "$add_this")
# same output
Or with printf
:
$ printf "%s%s\n" "$(cat file)" "$add_this"
# same output
Bottom line is you are only adding two pieces of text together and there are many ways in Unix to do that.
Then redirect the output of any of those (likely cat
) to a temp file then move the temp file onto the source file:
$ cat file <(echo "$add_this") >/tmp/tmp_file && mv /tmp/tmp_file file
$ cat file
line 1
line 2
line 3
# Gateway
10.0.0.1 schoolhost it20
# Addresses for the Windows
10.0.0.240 host1 it21
10.0.0.241 host2 it22
Upvotes: 0
Reputation: 531165
I don't see a need for sed
here. Just use cat
and a here document.
cat <<EOF >> hosts
# Gateway
10.0.0.1 schoolhost it20
# Addresses for the Windows
10.0.0.240 host1 it21
10.0.0.241 host2 it22
EOF
Upvotes: 1