开发者

replacing the `'` char using awk

I have li开发者_Python百科nes 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?


tr is made for this purpose

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

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


This works:

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


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
    


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 ('\'').


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.


This also works:

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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜