Print all Fields with AWK separated by OFS

心已入冬 提交于 2019-11-30 06:30:07

问题


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

回答1:


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'



回答2:


Sed equivalent:

$ echo "1 2 3 4" | sed 's/ /:-)/g'

Here's another option with awk:

$ echo "1 2 3 4" | awk '{ gsub(/\s/, ":-)")}1' 


来源:https://stackoverflow.com/questions/13704947/print-all-fields-with-awk-separated-by-ofs

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