tonyibm
tonyibm

Reputation: 641

how to not use default field separator in AWK

I have a string like this:

tony x25 xdata engineer Xhome

and i want to use awk to split this string with x or X,

awk '{FS="[xX]"} {for(i=1;i<=NF;i++) print $i}' 1

but the result is like this:

tony
x25
xdata
engineer
Xhome

Seems the default field separator of whitespace is still used, how to not use default field separator but only character x or X ?

Upvotes: 0

Views: 296

Answers (2)

oliv
oliv

Reputation: 13249

You should use the record separator RS instead of the the field separotor FS:

$ awk -v RS='[Xx]' 1 <<< "tony x25 xdata engineer Xhome"
tony
25
data engineer
home

Setting RS to the regex [Xx] allows to cut the string in pieces. These ones are printed using the output record separator ORS that is by default set to \n.

Upvotes: 1

Kent
Kent

Reputation: 195059

change your code into:

 awk 'BEGIN{FS="[xX]"} {for.....

or

 awk -F"[xX]" '{for(....

some detail:

If you don't put the FS in BEGIN block, when awk gets the first line, the default FS was used, that's why you got the output in your question. However, after the first line, the FS was set by [Xx], that is, from the 2nd line in your file, the fields would be separated by [Xx]. Unfortunately, your input example has only one line. You can add some more lines to test.

Upvotes: 4

Related Questions