Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the field separator to an empty string?

Tags:

awk

gawk

The awk manual indicates that both -v FS and -F are equivalent ways to set the field separator.

The GNU Awk User’s Guide -> 4.5.4 Setting FS from the Command Line:

FS can be set on the command line. You use the `-F' argument to do so.

(...)

The value used for the argument to `-F' is processed in exactly the same way as assignments to the built-in variable FS.

However, I noticed that there is a difference if we set it to an empty string, it is not the same. Tested on my GNU Awk 4.1.1.

This works:

$ awk -F, '{print $2}' <<< "a,b,c"
b
$ awk -v FS=, '{print $2}' <<< "a,b,c"
b

But this does not:

$ awk -F="" '{print $2}' <<< "abc"
                                      # $1 contains abc
$ awk -v FS="" '{print $2}' <<< "abc"
b

Why? Is this because setting FS to empty is a gawk specific?

like image 287
fedorqui 'SO stop harming' Avatar asked Dec 03 '25 09:12

fedorqui 'SO stop harming'


1 Answers

Looks like you can do this:

$ awk -F '' '{print $2}' <<< "abc"
b

Tested on GNU awk (versions 3.0.4 and 4.1.1) and mawk version 1.2

To be clear, the space between -F and '' is important!

like image 154
Tom Fenech Avatar answered Dec 06 '25 16:12

Tom Fenech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!