Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using awk in BASH alias or function

Tags:

bash

awk

I've a command that works just fine at the command line, but not when I try to put it in an alias or function.

$ awk '{print $1}' /tmp/textfile 0 

That's correct, as '0' is in position 1 of "textfile".

$ alias a="awk '{print $1}' /tmp/textfile" $ a 1 0 136 94 

That's the entire line in "textfile". I've tried every variety of quotes, parentheses and backticks that I could imagine might work. I can get the same problem in a wide variety of formats.

What am I not understanding?

like image 215
Corn-fuzed Avatar asked Aug 30 '11 14:08

Corn-fuzed


People also ask

What is the purpose of an alias in bash?

Aliases allow a string to be substituted for a word when it is used as the first word of a simple command. The shell maintains a list of aliases that may be set and unset with the alias and unalias builtin commands. The first word of each simple command, if unquoted, is checked to see if it has an alias.

What does awk command do in bash?

Awk is mostly used for pattern scanning and processing. It searches one or more files to see if they contain lines that matches with the specified patterns and then perform the associated actions. Awk is abbreviated from the names of the developers – Aho, Weinberger, and Kernighan.

Do aliases work in bash scripts?

BASH Alias is a shortcut to run commands using some mapping. It is a way to create some shortcut commands for repetitive and multiple tasks. We create an alias in a BASH environment in specified files.

What does $1 $2 indicate in awk file?

The variable $1 represents the contents of field 1 which in Figure 2 would be "-rwxr-xr-x." $2 represents field 2 which is "1" in Figure 2 and so on. The awk variables $1 or $2 through $nn represent the fields of each record and should not be confused with shell variables that use the same style of names.


2 Answers

You need to escape the $ like so:

 alias a="awk '{print \$1}' /tmp/textfile" 

Otherwise your alias is:

 awk '{print }' /tmp/textfile 

Which prints the whole file...

like image 51
Linus Kleen Avatar answered Sep 30 '22 08:09

Linus Kleen


Use a function instead of alias

myfunc(){ awk '{print $1}' file; } 
like image 43
ghostdog74 Avatar answered Sep 30 '22 06:09

ghostdog74