在编写 munin 脚本时,我经常必须解析配置文件以查找某些路径。
没有强标记(即不是 XML)的配置文件的问题是这些路径可以有多种语法:
- 单引号 (') 或双引号 (") 或不带引号
- 包含空格(如果字符串未加引号则转义)
- 包含引号(通常是单引号)
例如,我正在寻找一种方法来解析以下几行,以便提取路径(这次是在第一个位置):
/mnt/DirWithoutSpaces/ "Dir1" cnidscheme:dbd perm:0775 options:usedots,upriv
/mnt/Dir\ With\ Space/ Dir2 cnidscheme:dbd options:usedots,upriv
"/mnt/Dir With Space And D-quote" Dir3
'/mnt/Dir With Space And S-quote' Dir4
~/ "Dir 5" cnidscheme:dbd
"/mnt/Dir'ed" "Dir 6" cnidscheme:dbd
我通常使用 ERE
和 =~
bash 运算符 ([[ $string =~ $pattern ]]
) 但每次都是真是头疼。
我非常确定变量修改、cut
、awk
、sed
中的任何一个都非常有用,并且可以自动处理引号和其他东西,但我找不到那个特殊的神奇配方。
最佳答案
您可以在 grep
中尝试 -P (--perl-regexp)
选项:
$ grep -oP "^(\\\\ |[^ '\"])*" input.txt
/mnt/DirWithoutSpaces/
/mnt/Dir\ With\ Space/
~/
$ grep -oP "^(['\"]).*?\1" input.txt
"/mnt/Dir With Space And D-quote"
'/mnt/Dir With Space And S-quote'
"/mnt/Dir'ed"
$ grep -oP "^(['\"]).*?\1|^(\\\\ |[^ '\"])*" input.txt
/mnt/DirWithoutSpaces/
/mnt/Dir\ With\ Space/
"/mnt/Dir With Space And D-quote"
'/mnt/Dir With Space And S-quote'
~/
"/mnt/Dir'ed"
关于string - 解析字符串以查找可能引用的字段的通用 shell/bash 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10134129/