5

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!

2 Answers 2

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
3
  • 2
    Aliases 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
    Feb 15, 2012 at 12:08
  • You should name the alias something like awkc instead. Feb 15, 2012 at 14:58
  • I like the aliasing idea - with @glenn's modification - thanks all!
    – evsmith
    Feb 15, 2012 at 17:36
5

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.

2
  • Thanks - I'd forgotten that there was an option for field separator.
    – evsmith
    Feb 15, 2012 at 17:37
  • I am just curious if it is possible to change the awk defaults permanently in its config file?
    – WYSIWYG
    Jun 13, 2014 at 8:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .