一尘不染

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

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!


阅读 805

收藏
2020-06-07

共1个答案

一尘不染

应该这样做:

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
2020-06-07