【问题标题】:comand to convert closed single quote to single quote in unix在 unix 中将闭合单引号转换为单引号的命令
【发布时间】:2016-07-26 09:03:30
【问题描述】:

我有标签 sereated 文件。给出一个场景。 包含记录 ’RAZ’.here 它是关闭单引号我想同时用单引号 'RAZ' 全局替换它 如果关闭的单引号在我不想替换的某个单词的中间。

例如:

NAME|SUB
`RAZ` |Rockpor`t

我试过下面的命令

sed -i "s/\’/'/g"  Test.txt

输出:

'RAZ'|Rockpor't

期望的输出应该是:

'RAZ'|Rockpor`t

请指教。

【问题讨论】:

  • 您在问题文本中使用的引号 (’ U+0060) 与示例数据 (` U+2019) 中使用的引号不同。

标签: perl shell unix awk sed


【解决方案1】:

你可以这样做

你的输入文件,比如 /tmp/abc.txt 看起来像

#cat /tmp/abc.txt
`ABC`|REsaff`t|`rest`
`PQR`|sasdasd`y|d`souza

现在,运行这个命令

cat /tmp/abc.txt | sed s?\|?\\n\|?g | sed s?^\`?\'?g | sed s?\`\$?\'?g | sed s?^\|\`?\|\'?g | tr '\n' '#' | sed s?#\|?\|?g | tr '#' '\n'

该命令的作用是,它分离所有选项卡值,如果选项卡的值以`开头和结尾,则替换为',然后再次将所有选项卡合并在一起。

期望的输出:

'ABC'|REsaff`t|'rest'
'PQR'|sasdasd`y|d`souza

此解决方案适用于任意数量的选项卡。如果字符位于制表符的开头或结尾,则字符 ` 将在所有制表符中被替换。

注意:我在这里使用的分隔符是# 来分隔换行符,您可以相应地使用任何一个。

【讨论】:

    【解决方案2】:

    使用下面的代码。希望它有所帮助。

     sed 's/`/'"'"'/;s/`/'"'"'/' test.txt
    

    我用 " 来转义单引号函数。参考下面的截图.graditude

    【讨论】:

      【解决方案3】:

      这个 perl 命令会帮你搞定

      perl -pe "s/`(?![a-z])|(?<![a-z])`/'/ig"
      

      它会替换所有前面没有或后面没有字母的反引号

      输出

      NAME|SUB
      'RAZ' |Rockpor`t
      

      【讨论】:

        【解决方案4】:

        我建议

        perl -pe 's/(^|\W)`(.*?)`($|\W)/$1\x27$2\x27$3/g'
        

        展开

        perl -pe '
            $q = "\x27";  # a single quote
            s{
                (^|\W)    # start of line or a non-word char
                `         # the open quote
                (.*?)     # some non-quote characters
                `         # the close quote
                ($|\W)    # end of line or a non-word char
            }{$1$q$2$q$3}gx
        '
        

        演示

        perl -pe '$q="\x27"; s/(^|\W)`(.*?)`($|\W)/$1$q$2$q$3/g' <<'END'
        `foo`|I have James` hat|doesn`t
        END
        
        'foo'|I have James` hat|doesn`t
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-30
          • 2018-01-07
          • 1970-01-01
          • 2017-12-29
          • 2017-03-11
          • 2019-10-29
          相关资源
          最近更新 更多