How to Use Custom Field Separators (FS and OFS) in awk on Linux

By default, the awk language engine on Linux assumes that all incoming data is delimited by standard whitespace (spaces or tabs), and that all outgoing data should be separated by a single space. If you are parsing chaotic, non-standard files (like a CSV) and must fundamentally alter how the engine perceives and structures data at the kernel level, you must overwrite the FS and OFS internal variables.

Executing the Separator Overwrite Matrix

The awk engine constantly monitors two critical state variables that dictate its entire geometric parsing architecture.

  • FS (Field Separator): This variable tells the engine exactly how to shatter an incoming line of text into geometric array columns ($1, $2).
  • OFS (Output Field Separator): This variable tells the engine exactly what character to inject between those columns when you execute a print $1, $2 command.

To prevent chaotic data corruption, you must overwrite these variables before the engine reads the first line of the file. You must deploy the BEGIN block.

Deploying the Custom Formatting Vector

Imagine you have a file named database.csv. The incoming data is separated by commas (,). You must mathematically parse this data, extract columns 1 and 3, and output them separated by a solid geometric pipe character (|).

To execute the structural overwrite, open your terminal and type the precise command:

awk 'BEGIN { FS=","; OFS=" | " } { print $1, $3 }' database.csv

Analyzing the Parsing Calculus

The exact millisecond you execute this script, the awk engine intercepts the payload.

  • The engine triggers the BEGIN block before opening the data stream.
  • It violently overwrites its internal RAM. It changes FS to a comma. It changes OFS to the string " | ".
  • The engine then opens database.csv. It reads the first line (e.g., “John,Smith,Admin,55”).
  • Because FS is now a comma, the engine mathematically shatters the string perfectly: $1="John", $2="Smith", $3="Admin".
  • The engine hits the print $1, $3 command.
  • The engine outputs “John”. It sees the comma in the print statement, which triggers the OFS protocol. It injects the custom OFS string (" | "). It then outputs “Admin”. The absolute resulting output is: John | Admin.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.