2013-05-06 148 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