需要使用字符串/变量进行修补
我正在编写一个脚本来自动化在计算机实验室中设置一堆 Mac 的过程。
每个系统都是唯一标识的,我需要一种方法,使用相同的字符串在多个位置修补 plist 文件,该字符串将从脚本中的用户读取 这是一个 bash 脚本
原始字符串始终是相同的。修补字符串是可变的,具体取决于运行脚本的系统的身份。该字符串是在脚本开始时出于各种其他目的从用户处读取的,并存储在 $macnum 中。
有人可以为我提供一个可以编写脚本来执行任务的简单解决方案吗?谢谢。
I am writing a script to automate the process of setting up a bunch of Mac's in a computer lab.
Each system is uniquely identified and I need a method of patching a plist file in several locations with the same string that will be read from the user in the script which is a bash script
The original string is always the same. The patching string is variable depending on the identity of the system the script is being run on. This string is read from the user at the start of the script for various other purposes and stored in $macnum.
Can anybody please provide me a simple solution that can be scripted to perform the task? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以在plist中使用一些唯一标识符(例如
{{MACHINE_ID}}
)并使用sed
来替换它:You can use some unique identifier (e.g.
{{MACHINE_ID}}
) in the plist and usesed
to replace it:其中
-i
表示“就地”编辑文件,而/g
表示每行进行多次替换,如果只有一次则可以删除。Where
-i
means edit the file "in-place" and/g
says make the substitution multiple times per line and can be dropped if there is only one.如果您要更改的 plist 是 XML 格式,则 strager 和 msw 给出的基于 sed 的方法可以正常工作,但如果它是 Apple 的二进制格式,则可能会损坏文件格式。您可以先使用 plutil 将其转换为 XML:
之后不必将其转换回二进制格式,因为 Apple 的 plist 框架可以互换地读取这两种格式。另一种方法是使用 PlistBuddy 编辑 plist 的内容(尽管它需要脚本知道将哪些条目设置为哪些值,而不是仅仅替换占位符):
最后,您可以使用默认值执行相同的操作,尽管它要求您通过完整路径指定 .plist 文件,并保留 .plist 的名称:
The sed-based approach strager and msw gave will work fine if the plist you're changing is in XML format, but if it's in Apple's binary format it'll probably corrupt the file format. You can use plutil to convert it to XML first:
It shouldn't be necessary to convert it back to binary format afterward, as Apple's plist frameworks read the two formats interchangeably. Another approach would be to use PlistBuddy to edit the contents of the plist (although it'll require the script to know what entries to set to what values, rather than just replacing a placeholder):
Finally, you can do the same thing with defaults, although it requires you specify the .plist file by full path, and leave the .plist off its name: