Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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!

share|improve this question

2 Answers 2

up vote 1 down vote accepted

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
share|improve this answer
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 '12 at 12:08
    
You should name the alias something like awkc instead. –  glenn jackman Feb 15 '12 at 14:58
    
I like the aliasing idea - with @glenn's modification - thanks all! –  evsmith Feb 15 '12 at 17:36

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.

share|improve this answer
    
Thanks - I'd forgotten that there was an option for field separator. –  evsmith Feb 15 '12 at 17:37
    
I am just curious if it is possible to change the awk defaults permanently in its config file? –  bharat_iyengar Jun 13 at 8:35

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.