string - 解析字符串以查找可能引用的字段的通用 shell/bash 方法?

标签 string bash parsing textfield

在编写 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 ]]) 但每次都是真是头疼。

我非常确定变量修改、cutawksed 中的任何一个都非常有用,并且可以自动处理引号和其他东西,但我找不到那个特殊的神奇配方。

最佳答案

您可以在 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/

相关文章:

检查数组中是否存在字符串,如果不存在则将其添加到C中的数组中

macos - OS X Shell - 'Clickable' 删除文件的脚本?

python - 错误 : command 'gcc' failed with exit status 1 on CentOS

python - BeautifulSoup : Parsing "Span" element

java - 将 Java 字符串转换为 sql.Timestamp

c# - 使用utf16编码将字符串写入流

c - 不使用指针反转字符串

java - 在每一项但不是最后一项后插入逗号

bash - 如何在 Bash 中抛出错误?

xml - JSTL - 解析不适​​用于具有命名空间的元素