0

我有一个将输入字符串写入 /etc/hosts 的代码

#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

但我不知道如何编写另一个小程序来查找“开始列表”和“结束列表”以删除其中的所有内容。

4

1 回答 1

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
于 2013-05-06T11:13:57.523 回答