awk(3)-awk getline

awk getline is mainly to pass the data of the shell command to awk.
When there is no redirection character | or < on the left and right, getline acts on the current file, and reads the first line of the current file to the variable var or $0 (no variable) that follows it. ;
When there are redirection characters | or < on the left and right, getline acts on the directional input file

1 and prints the first line of the file test:
$ awk 'BEGIN{"cat test" | getline;print $0}' to read a line, No variable, default assignment $0
$ awk 'BEGIN{"cat test" | getline line;print line}' Read a line, assign it to variable line
$ awk 'BEGIN{getline d < "test"; print d}' Read from file Take a line and assign it to the variable d
$ awk 'BEGIN{getline < "test"; print $0}'

2. To print all lines, use a loop in the above command:
$ awk 'BEGIN{while("cat test" | getline ) print $0}'
$ awk 'BEGIN{while("cat test" | getline d) print d}'
$ awk 'BEGIN{while(getline < " test") print $0}'
$ awk 'BEGIN{while(getline d < "test") print d}' Note that variables used in awk are used directly, no need to add $ symbol

3, getline condition is not BEGIN
$ awk '{getline; print $0"#"$4} ' test
running process:
1), awk reads a line of data, starts executing
2), getline reads the next line of data, replacing $0, $1, $2.... (some versions of awk do not support dynamic update $0, or $0 is updated, and the values ​​of $1 and $2 are not updated. You can use gawk or nawk instead, or use awk's split function to process). At this time, the $0 and $4 printed are the next line of data.
3), then awk reads a line of data, and then executes the second step. So only the even lines of the file are printed.

4. Receive user input
4.1. Prompt the user to input
$ awk 'BEGIN{print "input sth";getline var <"-" ; print var}' # where "-" is the standard input

5. You can use system("system command" ) can also be a custom function, but data cannot be transferred between shell commands and awk, so it can only be used to process individual system data.
Example: Redirect standard output of date command to date.log file
$ awk 'BEGIN{system("date > date.log")}'

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326741636&siteId=291194637
awk