我有一个文件,其中列出了所有服务器,例如 lserver :
$ cat lserver
A1
A2
A3
我想创建一个 shell 脚本来注释 lserver 中的任何服务器示例:
$ stopm.sh A2
$ cat lserver
A1
#A2
A3
并从 lserver 中取消注释服务器:例如
$ startm.sh A2
$ cat lserver
A1
A2
A3
有什么建议吗?
答案1
评论:
server=A2; sed -i "/^$server/ c#$server" file.txt
取消注释:
server=A2; sed -i "/^#$server/ c$server" file.txt
答案2
尝试以下功能:
function comment() {
local regex="${1:?}"
local file="${2:?}"
local comment_mark="${3:-#}"
sed -ri "s:^([ ]*)($regex):\\1$comment_mark\\2:" "$file"
}
function uncomment() {
local regex="${1:?}"
local file="${2:?}"
local comment_mark="${3:-#}"
sed -ri "s:^([ ]*)[$comment_mark]+[ ]?([ ]*$regex):\\1\\2:" "$file"
}
用法:
comment REGEX FILE [COMMENT-MARK]
uncomment REGEX FILE [COMMENT-MARK]
COMMENT-MARK default value is #
对于你的情况,你这样做:
comment A2 /path/to/lserver
答案3
(server=A2; sed -ir -e "s/^$server\$/#\1/")
答案4
I have done by below script and it worked fine too
Scriptname
#!/bin/bash
echo "enter the servername"
read s1
sed -i "/$s1/s/^/#/g" filename
sed -i "s/^#//g" filename