Professional Documents
Culture Documents
Concept
Awk scans ascii files or standard input. It can search strings easily and then has a lot of
possibilities to process the found lines and output them in the new format. It does not
change the input file but sends its results onto standard output.
awk/nawk/gawk
Awk is the original awk. Nawk is new_awk and gawk the gnu_awk. The gnu_awk can do
most, but is not available everywhere. So best is to use only things which nawk can do,
because if that is not installed, then the system is not well anyway.
Variables
Awk does not distinguish between strings and numbers. So one may just put anything into
a variable with varname = othervar or varname = "string". To get it out of the var just
write it's name as a function argument or on the right side of any operator.
BEGIN
' a=$var
{
{
{
{
myvalue = 1700
myvalue -= $4
myvalue += $4
print myvalue
}
}
}
}
' infile
' infile
BEGIN
/myline/
}
END
{ count = 0 }
{
for(i=1;i<=NF;i++){
if(substr($i,3,2) == "ae"){
bla = "Found it on line: "
print bla NR " in field: " i
}
}
{ print "Found " count " instances of it" }
' infile
for(i=1;i<=NF;i++){
len = length($i)
for(j=len;j>0;j--){
char = substr($i,j,1)
tmp = tmp char
}
$i = tmp
tmp = ""
}
print
' infile
}
}
=
=
=
=
$1
$2
$3
$4
# Calculate
if(mytype == "foo"){
var1 *= 10
var2 += 20
var3 = log(var3)
}
if(mytype == "boo"){
var1 *= 4
var2 += 10
var3 = cos(var3)
}
# Print formated output in reverse order
}
printf("%-4s%10.3f%10.3f%10.3f\n",mytype,var3,var2,var1)
Functions
This example substitutes the first three occurrences of "searchterm" with a different term
in each case and from the fourth case it just prints the line as it is.
It should show where to place a function and how to call it.
#!/usr/bin/nawk -f
BEGIN{
mysub1
= "first_sub"
mysub2
= "second_sub"
mysub3
= "third_sub"
mycount = 1
find
= "searchterm"
}
{
if($0 ~ find){
if(mycount == 1){
if(mycount == 2){
if(mycount == 3){
if(mycount > 3){
replace(mysub1); }
replace(mysub2); }
replace(mysub3); }
print; }
}else{
}
mycount++
print
}
function replace(mysub) {
sub(find,mysub)
print
break
}
String functions
sub(regexp,sub)
sub(regexp,sub,var)
gsub(regexp,sub)
gsub(regexp,sub,var)
split(var,arr)
split(var,arr,sep)
index(bigvar,smallvar)
match(bigvar,expr)
length(var)
substr(var,num)
substr(var,num1,num2)
sprintf(format,vars)