Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print all Fields with AWK separated by OFS

Tags:

awk

gawk

Is there a way to print all records separated by the OFS without typing out each column number.

#Desired style of syntax, undesired result [kbrandt@glade: ~] echo "1 2 3 4" | gawk 'BEGIN { OFS=" :-( "}; {print $0}'         1 2 3 4  #Desired result, undesired syntax [kbrandt@glade: ~] echo "1 2 3 4" | gawk 'BEGIN { OFS=" :-) "}; {print $1,$2,$3,$4}' 1 :-) 2 :-) 3 :-) 4 
like image 613
Kyle Brandt Avatar asked Dec 04 '12 14:12

Kyle Brandt


People also ask

How do I print all columns in awk?

With space as the separator you could even generalize the solution; e.g., the following returns everything from the 3rd field: awk '{sub(/^[ ]*([^ ]+ +){2}/, ""); print $0}' It gets trickier with arbitrary field separators, though.

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 use the field separator in awk?

Any special characters in the field separator must be escaped appropriately. For example, to use a ' \ ' as the field separator on the command line, you would have to type: # same as FS = "\\" awk -F\\\\ '…' files … Because ' \ ' is used for quoting in the shell, awk sees ' -F\\ '.


1 Answers

This is a variation on the first style:

echo "1 2 3 4" | gawk 'BEGIN { OFS=" :-( "}; {$1=$1; print $0}' 

Results:

1 :-( 2 :-( 3 :-( 4 

Explanation:

the $1=$1 is to rebuild the record, using the current OFS (you can also see http://www.gnu.org/software/gawk/manual/gawk.html#Changing-Fields)

Update:

(suggested by @EdMorton and @steve) This is a briefer, equivalent version of the awk command, that sets OFS in the command line, and takes advantage of print $0 as the default action:

awk -v OFS=" :-( " '{$1=$1}1' 
like image 153
German Garcia Avatar answered Oct 01 '22 13:10

German Garcia