【发布时间】:2015-12-20 11:15:33
【问题描述】:
我是 shell 编程的新手,必须完成以下任务。 我在第 28 行(静态)有以下行的文件。
page.sysauth = "Admin"
我想在每次创建新的 sysauth 条目时使用 shell 脚本替换这一行。
page.sysauth = {"Admin", "root"} page.sysauth = {"Admin", "root", "newAdmin"} 等等
我还想从这个 sysauth 变量中删除条目
page.sysauth = {"Admin", "root", "newAdmin"}
page.sysauth = {"Admin", "root"}
page.sysauth = "Admin"
请提供实现这一目标的指针。
编辑: 感谢您的输入: 假设:应该存在第一个条目。例如:page.sysauth="Admin" 当 page.sysauth=______(空)时脚本失败。
这是我的工作脚本 sysauth_adt.sh
#!/bin/bash
add () {
sed -i~ -e '28 { s/= "\(.*\)"/= {"\1"}/; # Add curlies to a single entry.
s/}/,"'"$entry"'"}/ # Add the new entry.
}' "$file"
}
remove () {
sed -i~ -e '28 { s/"'"$entry"'"//; # Remove the entry.
s/,}/}/; # Remove the trailing comma (entry was last).
s/{,/{/; # Remove the leading comma (entry was first).
s/,,/,/; # Remove surplus comma (entry was inside).
s/{"\([^,]*\)"}/"\1"/ # Remove curlies for single entry.
}' "$file"
}
if (( $# == 3 )) ; then
file=$1
action=$2
entry=$3
if [[ $action == add ]] ; then
if head -n28 $1 | tail -n1 | grep -q $3 ; then
echo 0
else
add
fi
elif [[ $action == remove ]] ; then
if head -n28 $1 | tail -n1 | grep -q $3 ; then
remove
else
echo 0
fi
fi
else
echo "Usage: ${0#*/} file (add | remove) entry" >&2
exit 1
fi
【问题讨论】: