Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replacing the `'` char using awk

Tags:

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?

like image 343
SIMEL Avatar asked Jun 29 '11 12:06

SIMEL


People also ask

How do I replace text in awk?

awk has two functions; sub and gsub that we can use to perform substitutions. sub and gsub are mostly identical for the most part, but sub will only replace the first occurrence of a string. On the other hand, gsub will replace all occurrences.

What is awk '{ print $2 }'?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output. xargs kill -${2:-'TERM'} takes the process IDs from the selected sidekiq processes and feeds them as arguments to a kill command.

How do you remove the last character in awk?

This method works as our given string pipes with the awk and then in awk, the string is processed. Here the length($0)-1 means removing the last character by deducting '1' from the string's total length. Through this process, the command will print the string from the 1st character up to the 2nd character.

How do I specify a delimiter in awk?

The AWK Field Separator (FS) is used to specify and control how AWK splits a record into various fields. Also, it can accept a single character of a regular expression. Once you specify a regular expression as the value for the FS, AWK scans the input values for the sequence of characters set in the regular expression.


2 Answers

tr is made for this purpose

echo test\'\'\'\':::string | tr -d \': teststring  $ echo test\'\'\'\':::string | awk '{gsub(/[:\47]*/,"");print $0}' teststring 
like image 75
Fredrik Pihl Avatar answered Nov 20 '22 10:11

Fredrik Pihl


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 
like image 39
Dimitre Radoulov Avatar answered Nov 20 '22 10:11

Dimitre Radoulov