仅使用bash /标准Linux命令去除字符串中的单引号和双引号

我正在寻找仅使用bash /标准Linux命令即可将字符串转换为以下内容的东西:

  1. Single-quotes surrounding a string should be removed
  2. Double-quotes surrounding a string should be removed
  3. Unquoted strings should remain the same
  4. Strings with unmatched surrounding quotes should remain the same
  5. Single-quotes that don’t surround the string should remain
  6. Double-quotes that don’t surround the string should remain

例如:

  • ‘Food’ should become Food
  • “Food” should become Food
  • Food should remain the same
  • ‘Food” should remain the same
  • “Food’ should remain the same
  • ‘Fo’od’ should become Fo’od
  • “Fo’od” should become Fo’od
  • Fo’od should remain the same
  • ‘Fo”od’ should become Fo”od
  • “Fo”od” should become Fo”od
  • Fo”od should remain the same

Thank you!

回答:

应该这样做:

sed "s/^\([\"']\)\(.*\)\1\$/\2/g" in.txt

其中in.txt是:

"Fo'od'

'Food'

"Food"

"Fo"od'

Food

'Food"

"Food'

'Fo'od'

"Fo'od"

Fo'od

'Fo"od'

"Fo"od"

Fo"od

而Expected.txt是:

"Fo'od'

Food

Food

"Fo"od'

Food

'Food"

"Food'

Fo'od

Fo'od

Fo'od

Fo"od

Fo"od

Fo"od

您可以检查它们是否符合:

diff -s <(sed "s/^\([\"']\)\(.*\)\1\$/\2/g" in.txt) expected.txt

以上是 仅使用bash /标准Linux命令去除字符串中的单引号和双引号 的全部内容, 来源链接: utcz.com/qa/427791.html

回到顶部