本文介绍了仅使用bash/标准Linux命令去除字符串中的单引号和双引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking for something that will translate a string as follows, using only bash / standard Linux commands:

  1. 应删除字符串中的单引号
  2. 应删除字符串中的双引号
  3. 未加引号的字符串应保持不变
  4. 带有不匹配的引号的字符串应保持不变
  5. 不包含字符串的单引号应保留
  6. 不包含字符串的双引号应保留

例如:

  • 食物"应成为食物
  • 食物"应成为食物
  • 食物应该保持不变
  • 食物"应保持不变
  • 食物"应保持不变
  • 'Fo'od'应该成为Fo'od
  • "Fo'od"应成为Fo'od
  • 注意事项应该保持不变
  • 'Fo'od'应该成为Fo'od
  • "Fo" od应该变成Fo" od
  • 焦点"应保持不变
  • '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

谢谢!

推荐答案

这应该做到:

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

in.txt在哪里:

Where in.txt is:

"Fo'od'
'Food'
"Food"
"Fo"od'
Food
'Food"
"Food'
'Fo'od'
"Fo'od"
Fo'od
'Fo"od'
"Fo"od"
Fo"od

expected.txt是:

And expected.txt is:

"Fo'od'
Food
Food
"Fo"od'
Food
'Food"
"Food'
Fo'od
Fo'od
Fo'od
Fo"od
Fo"od
Fo"od

您可以检查它们是否与以下项匹配:

You can check they match with:

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

这篇关于仅使用bash/标准Linux命令去除字符串中的单引号和双引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 18:46