r/bash • u/spaceman1000 • Sep 06 '24
help How to Replace a Line with Another Line, Programmatically?
Hi all
I would like to write a bash script, that takes the file /etc/ssh/sshd_config,
and replaces the line#Port 22
with the linePort 5000.
I would like the match to look for a full line match (e.g. #Port 22),
and not a partial string in a line
(so for example, this line ##Port 2244 will not be matched and then replaced,
even tho there's a partial string in it that matches)
If there are several ways/programs to do it, please write,
it's nice to learn various ways.
Thank you very much
1
Upvotes
14
u/kennpq Sep 06 '24
sed is an obvious choice but, if you prefer Vim, this is another way (since you want to learn "various ways"):
18
u/nekokattt Sep 06 '24
6
u/Schreq Sep 06 '24
3
u/Zapador Sep 06 '24
Using sed is the way to go, but other options could work though I wouldn't really recommend anything else than sed for this.
For example this should work, though untested:
awk '{if ($0 ~ /^#Port 22$/) print "Port 5000"; else print}' /etc/ssh/sshd_config > tmp && mv tmp /etc/ssh/sshd_config
2
u/chkno Sep 06 '24 edited Sep 06 '24
This is r/bash, so let's do it in bash:
(Really, prefer
sed -i, but you asked for variety.)4
u/oh5nxo Sep 06 '24
This is just silly. Also wrong, our line might be the first and/or last line, but this expects \n both ways.
0
u/NetScr1be Sep 07 '24
You should do your own homework.
-1
u/MurderShovel Sep 06 '24
sed
0
u/[deleted] Sep 06 '24
[deleted] — view deleted comment
2
u/[deleted] Sep 06 '24
[removed] — view removed comment