用PlistBuddy修改Plist文件

Plist文件是以.plist为结尾的文件的总称. 众所周知, Plist在Mac OSX系统中起着举足轻重的作用,就如同Windows里面的Registry一样,系统和程序使用Plist文件来存储自己的安装/配置/属性等信息。正如可以使用命令行命令来处理大多数系统管理一样,操作Plist文件也是系统提供的。    

所幸有PlistBuddy工具,这个工具通过它的简单语法就可以操作嵌套的键值。如果你的系统没有PlistBudy可以安装苹果的开发工具。

基本的使用可以查看man文档或者是在线帮助:

$ plistbuddy -h
Command Format:
    Help - Prints this information
    Exit - Exits the program, changes are not saved to the file
    Save - Saves the current changes to the file
    Revert - Reloads the last saved version of the file
    Clear [<Type>] - Clears out all existing entries, and creates root of Type
    Print [<Entry>] - Prints value of Entry.  Otherwise, prints file
    Set <Entry> <Value> - Sets the value at Entry to Value
    Add <Entry> <Type> [<Value>] - Adds Entry to the plist, with value Value
    Copy <EntrySrc> <EntryDst> - Copies the EntrySrc property to EntryDst
    Delete <Entry> - Deletes Entry from the plist
    Merge <file.plist> [<Entry>] - Adds the contents of file.plist to Entry
    Import <Entry> <file> - Creates or sets Entry the contents of file
               
Entry Format:
    Entries consist of property key names delimited by colons.  Array items
    are specified by a zero-based integer index.  Examples:
        :CFBundleShortVersionString
        :CFBundleDocumentTypes:2:CFBundleTypeExtensions
               
Types:
    string
    array
    dict
    bool
    real
    integer
    date
    data
               
Examples:
    Set :CFBundleIdentifier com.apple.plistbuddy
        Sets the CFBundleIdentifier property to com.apple.plistbuddy
    Add :CFBundleGetInfoString string "App version 1.0.1"
        Adds the CFBundleGetInfoString property to the plist
    Add :CFBundleDocumentTypes: dict
        Adds a new item of type dict to the CFBundleDocumentTypes array
    Add :CFBundleDocumentTypes:0 dict
        Adds the new item to the beginning of the array
    Delete :CFBundleDocumentTypes:0 dict
        Deletes the FIRST item in the array
    Delete :CFBundleDocumentTypes
        Deletes the ENTIRE CFBundleDocumentTypes array

  

这里主要解释一下PlistBuddy的几个关键点.

  • 如何定义嵌套的键值: 正如前面说的它使用一种简单的描述方式,上一层的键值在前面,而每个键值之间使用":"符号分隔,比如:本文最初的例子中Software->Gallery->OnlineMarketplace表述为:":Software:Gallery:OnlineMarketplace", 第一个":"表示根.

  • 而如果键值的名称包含空格等特殊字符的时候,如同命令行的转义字符一样,使用"/"来转义,比如: ":Software:Gallery:Online/ Marketplace".

  • PlistBuddy如果不使用"-c"参数,则进入人机交互模式, "-c"的意思就是执行它后面的命令列表,而命令如果有参数,需要把它们包含在引号中,

1.添加

plistbuddy -c 'Add :Software:Gallery:Version string "1.0"' ~/Desktop/com.sample.plist

2.输出

plistbuddy -c "Print" ~/Desktop/com.sample.plist

3.修改

plistbuddy -c 'Set :Software:Gallery:Version "1.1"' ~/Desktop/com.sample.plist

4.删除

plistbuddy -c 'Delete :Software:Gallery:Version' ~/Desktop/com.sample.plist

5.合并

plistbuddy -c "Merge ~/Desktop/Global.plist :Software:Gallery" ~/Desktop/com.sample.plist

原文地址:https://www.cnblogs.com/greywolf/p/3460532.html