如何使awk产生列 [英] How to make awk produce columns
本文介绍了如何使awk产生列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含两列的文件.此文件中的每一行都有不同的单词大小
I have a file with two columns. Each line in this file has a different size of words
awk '$5=$9' FS="#" OFS="\t" file1**
Tomato#Vegetable
Orange#Fruit
Cucumber#Vegetable
Sweat Potato#Fruit
这行代码使它像这样:
Tomato Vegetable
Orange Fruit
Cucumber Vegetable
Sweat Potato Fruit
我正试图使该文件显示如下:
I am trying to make this file be displayed like this:
Tomato Vegetable
Orange Fruit
Cucumber Vegetable
Sweat Potato Fruit
我做错了什么却没有给我这个结果?
What am I doing wrong that does not give me this result?
推荐答案
在Unix/Linux中,您可以使用column
生成列输出:
With Unix / Linux you can use column
to produce column output:
$ column -t -s '#' your_file
Tomato Vegetable
Orange Fruit
Cucumber Vegetable
Sweat Potato Fruit
要在awk
中执行此操作,您可以读取文件两次以获取每一列的最大字段长度.完成此操作后,您可以使用
To do it in awk
you can read the file twice to get the max field length for each column. Once you do that, you can fix the field width with sprintf
with the field width + pad value:
awk -F'#' -v pad=4 '
FNR==NR { # FNR==NR means first file
for (i=1;i<=NF;i++) # find the max width of each field
if(max[i]<length($i)) max[i]=length($i)
next # next record of first file
}
{ # Second file
s="" # reset the buffer string
for (i=1;i<=NF;i++) # build the buffer field by field
s=s sprintf("%-*s%*s", max[i], $i, pad, "")
print s # print the buffer
} ' your_file your_file
打印:
Tomato Vegetable
Orange Fruit
Cucumber Vegetable
Sweat Potato Fruit
这篇关于如何使awk产生列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文