我正在尝试创建一个可以注释/取消注释 fstab 中特定行的脚本。
如果参数不是路径,则效果很好......
# add comment
sed -i '/db1/s/^/#DO NOT EDIT THIS LINE /g' /etc/fstab
# remove comment
sed -i '/db1/s/^#DO NOT EDIT THIS LINE //g' /etc/fstab
但是,如果我尝试使用带有正斜杠的变量,则它不起作用。
如果我有多个这样的条目,我只想评论其中的一些。
/dev/disk/by-uuid/f40f5a40-4772-479e-9041-330c3afbfb40 /oradata/db1 auto nosuid,nodev,nofail,x-gvfs-show 0 0
/dev/disk/by-uuid/f40f5a40-4772-479e-9041-330c3afbfb40 /oradata/db2 auto nosuid,nodev,nofail,x-gvfs-show 0 0
/dev/disk/by-uuid/f40f5a40-4772-479e-9041-330c3afbfb40 /oradata/db3 auto nosuid,nodev,nofail,x-gvfs-show 0 0
我尝试了各种解决方案,但没有任何效果。任何人都可以指出我正确的方向吗?
谢谢
答案1
像这样:
sed -i '/db1/s/^/#/g' /etc/fstab
或者与珀尔具有更强的匹配:
perl -i -pe 's/^/#/g if m!/oradata/db1!' /etc/fstab
如果你想要更强的匹配sed
:
sed -i '/oradata\/db1/s/^/#/g' /etc/fstab
输出
#/dev/disk/by-uuid/f40f5a40-4772-479e-9041-330c3afbfb40 /oradata/db1 auto nosuid,nodev,nofail,x-gvfs-show 0 0
/dev/disk/by-uuid/f40f5a40-4772-479e-9041-330c3afbfb40 /oradata/db2 auto nosuid,nodev,nofail,x-gvfs-show 0 0
/dev/disk/by-uuid/f40f5a40-4772-479e-9041-330c3afbfb40 /oradata/db3 auto nosuid,nodev,nofail,x-gvfs-show 0 0
答案2
考虑得好SED是S处理急诊科itor你可以更好地使用ed
如下:
ed -s /etc/fstab <<< $'/db1/s/^/#/\n,p'
如果上面看起来不错,只需将p
end 替换为w
p
= 打印
w
= 写入
如果您有兴趣全局替换所有出现的情况,那么您可以运行如下命令:
ed -s /etc/fstab <<< $'g/db1/s/^/#/\n,p'
再次替换p
为w
以写入文件。
因为<<<
需要bash
有其他方法来完成此任务。使用 Bourne shell 与printf
printf '%s\n' 'g/db1/s/^/#/' w q | ed -s /etc/fstab
或者没有 Bourne shellprintf
ed -s /etc/fstab <<!
g/db1/s/^/#/
w
q
!
答案3
经过相当多的测试后,我找到了解决我的问题的方法。
本质上,我必须将 MOUNTPOINT 变量替换为包含添加了转义字符的安装点路径的另一个变量。
MOUNTPOINTF="${MOUNTPOINT////\\/}
#!/bin/sh
FILE="./fstab"
TAG="#DO NOT EDIT THIS LINE "
COMMAND="do_mount"
f_usage(){
echo "usage: sudo_mount_oradata1.sh -h"
echo " sudo_mount_oradata1.sh -m /oradata1 [-u]"
exit 1;
}
f_mount() {
if grep -q "${MOUNTPOINT}" $FILE ; then
if grep -q "${TAG}" $FILE ; then
sed -i.bak "/${MOUNTPOINTF}/s/^${TAG}//g" $FILE
else
echo "INFO: fstab does not contains a commented entry for ${MOUNTPOINT}."
fi
else
echo "INFO: fstab does not contains an entry for ${MOUNTPOINT}."
fi
}
f_unmount() {
if grep -q "${MOUNTPOINT}" $FILE ; then
if grep -q "${TAG}" $FILE ; then
echo "INFO: Entry for ${MOUNTPOINT} is already commented in fstab."
else
sed -i.bak "/${MOUNTPOINTF}/s/^/${TAG} /g" $FILE
fi
else
echo "INFO: fstab does not contains an entry for ${MOUNTPOINT}."
fi
}
while getopts m:u opt
do
case "$opt" in
m) MOUNTPOINT="${OPTARG}" ; MOUNTPOINTF="${MOUNTPOINT////\\/}" ;;
u) COMMAND="do_unmount" ;;
*) f_usage ;;
esac
done
clear
# remove leading whitespace from each line
sed -i "s/^[ \t]*//" $FILE
case "$COMMAND" in
do_mount) f_mount ;;
do_unmount) f_unmount ;;
esac
# remove leading whitespace from each line
sed -i "s/^[ \t]*//" $FILE
# debug
echo;
cat $FILE
echo;
ls -lh $FILE*
exit 0