Is it possible to change the default field separator in awk?

3

I'm always using awk to manipulate comma separated files, so the first line in my code is always changing the field separator to "," like so:

awk 'BEGIN {FS=","}
$2 < 20 {print $1}' myfile.csv

Is it possible to change awk's defaults so that comma is the default FS? It's not a big problem, but it would just make things a bit neater. I tried googling, but didn't find anything useful; it might be that this isn't possible, but I thought I'd ask!

evsmith

Posted 2012-02-15T11:04:54.940

Reputation: 143

Answers

1

EDIT: In general, as has been highlighted in the comments, the safe way to use an alias is to use a different name, eg awkc

Create an alias which sets the Field Seperator to a comma. Put the alias in ~/.bashrc, or if ~/.bashrc sources (includes) ~/.bash_aliases, then put it there. You can subsequently override it again in your command to whateveryou like,

Be aware that if you use 'awk' as the name of your alias, your script is totally not portable. It will only run properly on a system which has that particular alias.

alias awkc='awk -F","'

Example (using the alias)

echo "a,b c" | awkc '{print $1" -- "$2}'  

Output

a -- b c

Peter.O

Posted 2012-02-15T11:04:54.940

Reputation: 2 743

2Aliases such as this one are dangerous. The risk is that someday you will ask yourself: but why the heck is my awk not splitting using spaces ? – Ouki – 2012-02-15T12:08:53.237

You should name the alias something like awkc instead. – glenn jackman – 2012-02-15T14:58:11.650

I like the aliasing idea - with @glenn's modification - thanks all! – evsmith – 2012-02-15T17:36:56.853

4

To change awk default field separator, use the -F <fs> option (fs being a simple character or a regular expression).

You can also change this fs with the awk internal variable FS.

Ouki

Posted 2012-02-15T11:04:54.940

Reputation: 1 017

Thanks - I'd forgotten that there was an option for field separator. – evsmith – 2012-02-15T17:37:42.983

I am just curious if it is possible to change the awk defaults permanently in its config file? – WYSIWYG – 2014-06-13T08:35:40.487