awk - oneliner vs multiple line .

Dear Awk Experts,

I can write oneliner some time but find difficulty writing like a flow of a program in multiple lines,

could you please help how to write awk program , like long awk programs, any help to start with,

For example,
How to write this in multiple line:

ls -l | awk '{sum+=$5}END{print sum}' 

what is equivalent of this in terms of file.awk if want to pass through a file.

Thanks,

I'm not sure what you're asking. If you just want to make the above script easier to read, the following is equivalent to the above script:

ls -l | awk '
{       sum+=$5}
END {   print sum}'

If you want to put your script in a file instead of typing it every time you run this command, put the following in a file named script.awk:

{       sum+=$5}
END {   print sum}

and then you can get the same results by typing the command:

ls -l | awk -f script.awk

If you just want to put all of this in a shell script, create a file named size_sum
containing:

#!/bin/ksh
ls -l | awk '
{       sum+=$5}
END {   print sum}'

replacing /bin/ksh in the first line with the absolute pathname of the shell you're using to run this script, then enter the commands:

chmod +x size_sum
if [ ! -d $HOME/bin ]
then    mkdir $HOME/bin
fi
mv size_sum $HOME/bin

and then you can run the script in any directory that is your current working directory by entering the command:

size_sum
1 Like

Don, Thanks a lot , your answer makes sense to me , thanks a lot.

You can also split any long line using \ at the end of the line.
Eks

ls -l | \
awk '
{ sum+=$5}
END \
{ print sum}'

The back-slashes are not at all required within quotes.

Its needed, if you split the line.

ls -l | \
awk '
{ sum+=$5 }
END
{ print sum}'

This gives error awk: cmd. line:3: END blocks must have an action part

Any pattern in awk expects the corresponding action to start on the same line as that of the ending pattern line. If no action is found on that line, the default action (print current record) is taken.

The BEGIN/END blocks are different. They must have some action and those actions (like for other patterns) must start on the BEGIN/END lines.

You may have:

BEGIN {
blah..blah..blah..
}

or

END {
blah..blah..blah..}
1 Like