Replace line in files using script.

First sorry for my bad english.
I have search the forum without finding anything I fully understand, so I ask here.

The problem:

I have a config file that I will chance onece a day. One line only.
I know the linenumber, and I also know the start of the line.
Line number 19, and the start of the line is "H: 10.0.0.9 60110 user1 user1"

I want to replace the whole line with a predefine variable $newline, the rest I have figured out for my self, but now I am stuck...

So... How do I locate the linenumber or the known start of the line, and how do I replace that line with a new line stored in a variable, then save and close the file...

The filename is "debsvr.cfg" and is located in "/var/etc/" on a debian server.

I am pretty new at shell scripting, so if you can please explain so my kid will understand it :stuck_out_tongue:

Many thanks in advance :slight_smile:

Hi, try this:

sed -i "19s/.*/$newline/" /var/etc/debsvr.cfg

sed is a stream editor. Since your using debian it will probably have the -i (in place) option. This command goes to line 19 and replaces everything on that line with the content of shell variable $newline and write the result back (in place) to the same file.

try:

sed "19s/.*/$newline/" debsvr.cfg

with awk:

awk -v c="$newline" '{ if(NR==19) { print c} else {print $0} } ' debsvr.cfg

Many many thanks :)))
I tried Scrutinizer's suggestion and it's works 100% together with the rest of the script :slight_smile: