简体   繁体   English

Bash - 仅使用awk打印矩阵的某些部分

[英]Bash - only printing certain parts of a matrix using awk

I want to read a matrix of numbers 我想读一个数字矩阵

1 3 4 5 
2 4 9 0

And only want my awk statement to print out the first and last, so 1 and 0. I have this so far, but nothing will print. 并且只希望我的awk语句打印出第一个和最后一个,所以1和0.我有这个到目前为止,但没有什么会打印。 What is wrong with my logic? 我的逻辑出了什么问题?

    awk 'BEGIN {for(i=1;i<NF;i++)
        if(i==1)printf("%d ", $i);
        else if(i==NF && i==NR)printf("%d ", $i);}'
$ awk '{ if (NR==1) { print $1}} END{print $NF}' matrix
1
0

The above awk program has two parts. 上面的awk程序有两个部分。 The first is: 首先是:

{ if (NR==1) { print $1}}

This prints the first field (column) of the first record (line) of the file. 这将打印文件的第一个记录(行)的第一个字段(列)。

The second part is: 第二部分是:

END{print $NF}

This parts runs only at the end after the last record (line) has been read. 这部分仅在读取完最后一条记录(行)后的末尾运行。 It prints the last field (column) of that line. 它打印该行的最后一个字段(列)。

awk 'NR==1{print $1;} END{print $NF;}'

Borrowing from unix.com , you can use the following: 借用unix.com ,您可以使用以下内容:

awk 'NR == 1 {print $1} END { print $NF }'

This will print the first column of the first line (NR == 1) and end input has finished (END), print the final column of the last line. 这将打印第一行的第一列(NR == 1)并且结束输入已完成(END),打印最后一行的最后一列。

If I understand the output format you're looking for, this code should capture those values and print them: 如果我理解您正在寻找的输出格式,此代码应捕获这些值并打印它们:

awk 'NR == 1 {F = $1} END { L = $NF ; printf("%d %d", F, L) }'

awk is line based, NR is the current record (line) number. awk是基于行的,NR是当前记录(行)号。 and awk is essentially match => action, 和awk基本上匹配=>动作,

echo "1 3 4 5
2 4 9 0" |
awk 'NR == 1 {print $1;}
    END {print $NF;}'

for the first record print the first field; 为第一个记录打印第一个字段; for the last record print the last field. 为最后一条记录打印最后一个字段。

由于awk有这么多解决方案,这里是sed的另一种方式。

sed -r ':a;$!{N;ba};s/\s+.*\s+/ /' file

另一种sed变种:

$ echo $'1 3 4 5\n2 4 9 0' | sed -n '1s/ .*//p;$s/.* //p'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM