Skip to content

/flags/awk/awk-field-separator-f

awk -F (field separator): split on commas, colons, tabs or a regex

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash) · GNU Awk 5.4.1updated
tool
awk
command
awk
flag
-F fs
default
a single space: split on runs of blanks, ignoring leading and trailing blanks

awk -F, '{print $2}' file.csv splits each line on commas instead of whitespace. -F sets the variable FS (field separator) before the program runs: a single character other than space is used literally, and a longer value is treated as an extended regular expression, so -F'[,;]' splits on commas or semicolons. -F '\t' splits on tabs. Writing BEGIN {FS=","} in the program is equivalent.

Examples

bash
echo 'root:x:0:0:root:/root:/bin/bash' | awk -F: '{print $1, $6}'
printf 'a\tb c\td\n' | awk -F'\t' '{print $2}'
echo 'x,y;z' | awk -F'[,;]' '{print $3}'
echo 'key = value' | awk -F' *= *' '{print $2}'
echo 'one,two' | awk 'BEGIN {FS=","} {print $2}'
echo 'a|b|c' | awk -F'|' '{print $2}'

Output

root /root
b c
z
value
two
b

Single space versus other values

bash
echo '  a   b  ' | awk '{print NF ": [" $1 "]"}'
echo '  a   b  ' | awk -F'[ ]' '{print NF ": [" $1 "]"}'
echo 'a,,b' | awk -F, '{print NF}'

Output

2: [a]
8: []
3

The default separator ignores leading blanks and treats a run of blanks as one, so the first line has 2 fields. A separator that matches exactly one space, written as the bracket expression [ ], gives an empty field for each extra space, and two adjacent commas give an empty field between them.

ValueSplits on
(default) or -F " "Runs of spaces, tabs and newlines; leading and trailing blanks ignored
-F,Every comma (empty fields kept)
-F:Every colon
-F'\t'Every tab
-F'[,;]'A comma or a semicolon (regex)
-F'|'A literal pipe (single character, not a regex)
-F'[|]'A literal pipe, written as a bracket expression

Output separator

-F changes only how input is split. Set OFS to choose what print $1, $2 puts between fields, and assign a field ($1=$1) to rebuild $0 with the new separator:

bash
echo 'a:b:c' | awk -F: -v OFS=',' '{$1=$1; print}'

Output

a,b,c

Sources