2013-05-06 150 views
0

文本我有一个代码来写输入字符串/ etc/hosts中使用AppleScript删除从文件

#Host Database 
# 
# localhost is used to configure the loopback interface 
# when the system is booting. Do not change this entry. 
## 
127.0.0.1 localhost 
255.255.255.255 broadcasthost 
::1    localhost 
fe80::1%lo0 localhost 

# Start List 
173.252.100.26 abc.com 
173.252.100.26 xyz.com 
# End List 

,但我不知道怎么写其他的AppleScript找到“启动列表”和“最终名单”删除其中的所有内容。

回答

1

这可以用类似sudo osascript Untitled.scpt的东西运行。它不会在字符串之前或之后删除换行符。

set f to POSIX file "/etc/hosts" 
set input to read f as «class utf8» 
set o1 to offset of "# Start List" in input 
set o2 to (offset of "# End List" in input) + 10 
if o1 is 0 or o2 is 0 or o1 > o2 then return 
if o1 is 1 then 
    set s to "" 
else 
    set s to text 1 thru (o1 - 1) of input 
end if 
if (o2 - 1) is length of input then 
    set e to "" 
else 
    set e to text o2 thru -1 of input 
end if 
{s, e} 
set output to result as text 
set b to open for access f with write permission 
set eof b to 0 
write output to b as «class utf8» 
close access b 

或者只是使用SED:

sudo sed -i '' '/^# Start List$/,/^# End List$/d' /etc/hosts