How to use regex as field separator in awk?
You have mucked up your quotes and syntax. To set the input field separator, the easiest way to do it is with the -F
option on the command line:
awk -F '[0-9]' '{ print $1 }'
or
awk -F '[[:digit:]]' '{ print $1 }'
This would use any digit as the input field separator, and then output the first field from each line.
The [0-9]
and [[:digit:]]
expressions are not quite the same, depending on your locale. See "Difference between [0-9], [[:digit:]] and \d".
One could also set FS
in the awk
program itself. This is usually done in a BEGIN
block as it's a one-time initialisation:
awk 'BEGIN { FS = "[0-9]" } { print $1 }'
Note that single quotes can't be used in a single-quoted string in the shell, and that awk
strings always use double quotes.
+1 for Kusalananda's answer. Alternately, the FS variable can be set in the BEGIN block:
awk 'BEGIN {FS="[0-9]"} {print $1}'
Changing FS in a action block won't take effect until the next line is read
$ printf "%s\n" "abc123 def456" "ghi789 jkl0" | awk '{FS="[0-9]"; print $1}'
abc123
ghi
The other errors in the question:
- can't use single quotes inside a single-quoted string
==
is a comparison operator,=
is for variable assignment