sed to remove single and double quotes at the same time

后端 未结 7 2234
忘了有多久
忘了有多久 2020-12-28 20:38

I am trying to remove single quotes and double quotes from a file. Can I do it in a single sed command?

I am trying :

sed \'s/\\\"//g;s/\\\'//g\' tx         


        
相关标签:
7条回答
  • 2020-12-28 21:34

    Well, here's what I've came to.

    First, I found out with ord() what are codes for single and double quotes characters, and then used $(..) syntax to pass it into unquoted sed expression. I used XX and yy instead of empty strings. Obviously it is faaar from optimal, i.e. they perhaps should be combined into one expression, I encourage you to experiment with it. There are several techniques to avoid quoting problems, you can also put sed expression into separate file, to avoid it to be interpreted by shell. The ord() / chr() trick is also useful when trying to deal with single unreadable characters in output, e.g. UTF strings on non-UTF console.

    dtpwmbp:~ pwadas$ echo '"' | perl -pe 'print ord($_) . "\n";'
    34
    "
    dtpwmbp:~ pwadas$ echo "'" | perl -pe 'print ord($_) . "\n";'
    39
    '
    dtpwmbp:~ pwadas$ echo \'\" 
    '"
    dtpwmbp:~ pwadas$ echo \'\" | sed -e s/$(perl -e 'print chr(34) . "\n"')/XX/g | sed -e s/$(perl -e 'print chr(39) . "\n"')/yy/g 
    yyXX
    dtpwmbp:~ pwadas$
    

    EDIT (note that this time, both characters are replaced with the same string "yy").There might be some shell utilities for "translating" characters to character codes and opposite, i.e. it should be possible to do this without using perl or other language interpreter.

    dtpwmbp:~ pwadas$ echo \'\" | sed -e s/[`perl -e 'print chr(34) . chr(39)'`]/yy/g
    yyyy
    dtpwmbp:~ pwadas$ 
    

    and here's yet another way in shell, perhaps even simpler

    dtpwmbp:~ pwadas$ X="'"; Y='"' ; echo $X$Y; echo $X$Y | sed -e "s/$X/aa/g;s/$Y/bb/g"
    '"
    aabb
    dtpwmbp:~ pwadas$ 
    
    0 讨论(0)
提交回复
热议问题