How to use “:” as awk field separator?

夙愿已清 提交于 2019-11-27 09:02:12

问题


Given following command:

echo "1: " | awk '/1/ -F ":" {print $1}'

why does awk output:

1: 

回答1:


"-F" is a command line argument not awk syntax, try:

 echo "1: " | awk -F  ":" '/1/ {print $1}'



回答2:


If you want to do it programatically, you can use the FS variable:

echo "1: " | awk 'BEGIN { FS=":" } /1/ { print $1 }'

Note that if you change it in the main loop rather than the BEGIN loop, it takes affect for the next line read in, since the current line has already been split.




回答3:


You have multiple ways to set : as separator:

awk -F: '{print $1}'

awk -v FS=: '{print $1}'

awk '{print $1}' FS=:

awk 'BEGIN{FS=":"} {print $1}'

All of them are equivalent and for an will return 1 for a sample input "1:2:3":

$ awk -F: '{print $1}' <<< "1:2:3"
1
$ awk -v FS=: '{print $1}' <<< "1:2:3"
1
$ awk '{print $1}' FS=: <<< "1:2:3"
1
$ awk 'BEGIN{FS=":"} {print $1}' <<< "1:2:3"
1



回答4:


-F is an argument to awk itself:

$echo "1: " | awk -F":" '/1/ {print $1}'
1



回答5:


You can also use a regex as a field separator, the following will print "bar" by using a regex to set the number "10" as a separator.

echo "foo 10 bar" | awk -F'[0-9][0-9]' '{print $2}'



回答6:


AWK works as text interpreter that goes linewise for the whole document and that goes fieldwise for each line thus $1,$2..$n are references to the fields of each line($1 is the first field,$2 is the second field and so on...). You can define a field separator by using the "-F" switch under the command line or within two brackets with "FS=...". Now consider the answer of "JUERGEN" :

echo "1: " | awk -F  ":" '/1/ {print $1}'

Above the field boundaries are set by ":" so we have two fields $1 which is "1" and $2 which IS the empty space.After, comes the regular expression "/1/" that instructs the filter to output the first field only when the interpreter stumbles upon a line containing such an expression(i mean 1); The output of the "echo" command is one line that contains "1" so the filter will work...

When dealing with the following example :

echo "1: " | awk '/1/ -F ":" {print $1}'

The syntax is messy and the interpreter chose to ignore the part F ":" and switches to the default field splitter which is the empty space thus outputting "1:" as the first field and there will be not a second field!

The answer of JUERGEN contains the good syntax...




回答7:


No Need to write this much. Just put your desired field separator with -F option in awk command and the column number you want to print segregated as per your mentioned field separator.

echo "1: " | awk -F: '{print $1}'    
1

echo "1#2" | awk -F# '{print $1}'  
1



回答8:


Or you can use:

echo "1: " | awk  '/1/{print $1-":"}' 

This is really funny equation.



来源:https://stackoverflow.com/questions/2609552/how-to-use-as-awk-field-separator

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