cd /etc/squid/
SQUID=/etc/squid/squid.conf
WORD="acl blockclients src 192.168.5.0/255.255.255.0"
WORD1="acl banned src "/etc/squid/our_512kbps.txt""
WORD2="http_access deny banned"
WORD3="http_reply_access deny banned"
WORD4="http_access allow blockclients"
WORD5="http_reply_access allow all"
sed -i "s/LINE1/&\n$WORD/" $SQUID
sed -i "s/LINE2/&\n$WORD1/" $SQUID
sed -i "s/LINE3/&\n$WORD2/" $SQUID
sed -i "s/LINE4/&\n$WORD3/" $SQUID
sed -i "s/LINE5/&\n$WORD4/" $SQUID
sed -i "s/LINE6/&\n$WORD5/" $SQUID
我是Shell编程的新手,请任何人帮助我
我在这一行收到错误
WORD="acl blockclients src 192.168.5.0/255.255.255.0"
像
./internetblock.sh: line 7: blockclients: command not found
sed: -e expression #1, char 30: unknown option to `s'
答案 0 :(得分:1)
问题是WORD
包含/
,它也是sed
表达式分隔符。这就是sed
抛出错误的原因。解决此问题的最简单方法是使用文本中不存在的字符作为sed
分隔符,例如|
。
尝试更改sed
命令以使用|
代替/
:
sed -i "s|LINE1|&\n$WORD|" $SQUID
答案 1 :(得分:0)
将sed
与参数扩展一起使用非常棘手。鉴于您的问题的结构,迭代文件可能更合适:
cd /etc/squid/
SQUID=/etc/squid/squid.conf
WORD="acl blockclients src 192.168.5.0/255.255.255.0"
WORD1='acl banned src "/etc/squid/our_512kbps.txt"' # Use single quotes for embedded double quotes
WORD2="http_access deny banned"
WORD3="http_reply_access deny banned"
WORD4="http_access allow blockclients"
WORD5="http_reply_access allow all"
{
read LINE1
printf "%s\n%s\n" "$LINE1" "$WORD"
read LINE2
printf "%s\n%s\n" "$LINE2" "$WORD1"
read LINE3
printf "%s\n%s\n" "$LINE3" "$WORD2"
read LINE4
printf "%s\n%s\n" "$LINE4" "$WORD3"
read LINE5
printf "%s\n%s\n" "$LINE5" "$WORD4"
cat # Any remaining lines from the input file
} < "$SQUID"
如果您使用bash
或其他支持数组的shell,则可以大大缩短:
cd /etc/squid/
SQUID=/etc/squid/squid.conf
WORDS=( "acl blockclients src 192.168.5.0/255.255.255.0"
'acl banned src "/etc/squid/our_512kbps.txt"'
"http_access deny banned"
"http_reply_access deny banned"
"http_access allow blockclients"
"http_reply_access allow all" )
{ for word in "${WORDS[@]}"; do
read LINE;
printf "%s\n%s\n" "$LINE" "$word"
done
cat
} < "$SQUID"