Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

gawk - Print all Fields with AWK separated by OFS

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...