replacing the `'` char using awk

老子叫甜甜 提交于 2019-11-27 12:59:52

问题


I have lines with a single : and a' in them that I want to get rid of. I want to use awk for this. I've tried using:

 awk '{gsub ( "[:\\']","" ) ; print $0 }'

and

 awk '{gsub ( "[:\']","" ) ; print $0 }'

and

 awk '{gsub ( "[:']","" ) ; print $0 }'

non of them worked, but return the error Unmatched ".. when I put

 awk '{gsub ( "[:_]","" ) ; print $0 }'

then It works and removes all : and _ chars. How can I get rid of the ' char?


回答1:


You could use:

  1. Octal code for the single quote:

    [:\47]
    
  2. The single quote inside double quotes, but in that case special characters will be expanded by the shell:

    % print a\': | awk "sub(/[:']/, x)"        
    a
    
  3. Use a dynamic regexp, but there are performance implications related to this approach:

    % print a\': | awk -vrx="[:\\\']" 'sub(rx, x)'  
    a
    



回答2:


tr is made for this purpose

echo test\'\'\'\':::string | tr -d \':
teststring

$ echo test\'\'\'\':::string | awk '{gsub(/[:\47]*/,"");print $0}'
teststring



回答3:


This works:

awk '{gsub( "[:'\'']","" ); print}'



回答4:


With bash you cannot insert a single quote inside a literal surrounded with single quotes. Use '"'"' for example.

First ' closes the current literal, then "'" concatenates it with a literal containing only a single quote, and ' reopens a string literal, which will be also concatenated.

What you want is:

awk '{gsub ( "[:'"'"']","" ) ; print $0; }'

ssapkota's alternative is also good ('\'').




回答5:


I don't know why you are restricting yourself to using awk, anyways you've got many answers from other users. You can also use sed to get rid of " :' "

sed 's/:\'//g'

This will also serve your purpose. Simple and less complex.




回答6:


This also works:

awk '{gsub("\x27",""); print}'




回答7:


simplest awk '{gsub(/\047|:/,"")};1'



来源:https://stackoverflow.com/questions/6520816/replacing-the-char-using-awk

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!