Change the way AWK read file

2019-07-22 15:47发布

anyone could help me to achieve this ,normally AWK read file

a b c

as

$1:a
$2:b
$3:c

how to read this file

a
b
c

as

$1:a
$2:b
$3:c

Many thanks for help .

2条回答
老娘就宠你
2楼-- · 2019-07-22 15:56

Using GNU awk for multi-char RS:

$ cat file
a
b
c

d

$ awk -v RS='^$' '{for (i=1;i<=NF;i++) print "$"i"="$i; print "----"}' file
$1=a
$2=b
$3=c
$4=d
----

Note the difference wrt d with Tom's solution of setting RS to the NULL string:

$ awk -F'\n' -v RS='' '{for (i=1;i<=NF;i++) print "$"i"="$i; print "----"}' file
$1=a
$2=b
$3=c
----
$1=d
----

Think about how you want your script to behave if there are blank lines in the file.

查看更多
冷血范
3楼-- · 2019-07-22 16:01

You can unset the Record Separator and change the Input Field Separator to the newline character:

$ awk -F'\n' -vRS='' '{print $1,$2,$3}' file
a b c
查看更多
登录 后发表回答