Hi
JanneJannesson said:
The actual purpose of this wasn't for the scripts sake, it was to try and get a basic understanding of awk.
Then I am afraid my answer was not that helpful. :-( Let me try to explain.
Awk code is built from [tt]
pattern { action statements }[/tt] pairs, where
action statements get executed only if the
pattern evaluates to true. With the exception of some special patterns all such [tt]
pattern { action statements }[/tt] pairs get executed for each input record.
Both
pattern and
action statements can be left out ( but not in the same time ), in which case their default are used :[ul]
[li]default
pattern is
1, which being a logical true, means always[/li]
[li]default
action statements is
{print}, which being equivalent with
{print $0} prints out the current record[/li]
[/ul]
Code:
[navy]$0[/navy] [teal]=[/teal] NR [i][green]". "[/green][/i] [navy]$0[/navy]
[gray]# actually means :[/gray]
[navy]$0[/navy] [teal]=[/teal] NR [i][green]". "[/green][/i] [navy]$0[/navy] [teal]{[/teal] [b]print[/b] [teal]}[/teal]
[gray]# alternatively we can put our code in the action part and use no pattern :[/gray]
[teal]{[/teal] [b]print[/b] NR [i][green]". "[/green][/i] [navy]$0[/navy] [teal]}[/teal]
( As we set the current record ( [tt]$0[/tt] ) to current record number ( [tt]NR[/tt] ) concatenated with a piece of string and the current record, the result can never be false, so will always be printed. )
Here is a close rewrite of your original Perl code :
Code:
[gray]#!/usr/bin/awk -f[/gray]
[b]BEGIN[/b] [teal]{[/teal]
[b]print[/b] [i][green]"Specify the file you want to look at:"[/green][/i]
[b]getline[/b] file_name
[b]print[/b] [i][green]"This is the listed content of: "[/green][/i] file_name
line_n [teal]=[/teal] [purple]1[/purple]
[b]while[/b] [teal]([/teal]success [teal]=[/teal] [b]getline[/b] [teal]<[/teal] file_name[teal]) {[/teal]
[b]if[/b] [teal]([/teal]success [teal]==[/teal] -[purple]1[/purple][teal]) {[/teal]
[b]print[/b] [i][green]"Cannot open "[/green][/i] file_name [i][green]": "[/green][/i] ERRNO [teal]>[/teal] [i][green]"/dev/stderr"[/green][/i]
[b]exit[/b] [purple]1[/purple]
[teal]}[/teal]
[b]print[/b] line_n [i][green]". "[/green][/i] [navy]$0[/navy]
line_n[teal]++[/teal]
[teal]}[/teal]
[b]close[/b][teal]([/teal]file_name[teal])[/teal]
[teal]}[/teal]
Some explanations :[ul]
[li]The [tt]BEGIN[/tt] is a special pattern, means the action gets executed before processing the input file. As in this version there is no input file specified as command line parameter, there will be no automatic input processing. So we must use [tt]BEGIN[/tt] to have our code executed.[/li]
[li]There is no explicit file opening. The file gets opened when reading from it for the 1
st time. So we can do the error checking only after the [tt]getline[/tt] call.[/li]
[li]There is no [tt]die[/tt], the closes equivalent is to [tt]print[/tt] to stderr then to [tt]exit[/tt] with a non-zero exit code[/li]
[/ul]
Feherke.
feherke.github.io