This article link: http://blog.csdn.net/kongxx/article/details/8284952
A problem with today's work is that you need to filter out some of the command line output and output it in a tabular format
This assumes that the output of a command is as follows, assuming that we have filtered some of the columns or rows, which we store in Test.txt files
ID Name designation Department Salary Thomas Manager Sales $5,000 Jason Developer Technology $5,500 Sanjay Sysadmin Technology $7,000 Nisha Manager Marketing $9,500 Randy DBA Technology $6,000
Here is a simple awk file, which is saved to the Test.awk file.
function format (value, MaxLen, align) {
len=length (value);
Lendiff=maxlen-len;
if (lendiff>0) {for
(k=0, k<lendiff; k++) {
if (align== "right") {
value=value "";
} else {
value= "" VALUE;
}
}
}
return value;
}
BEGIN {
rows=0;
cols=5;
}
{
if (nf==cols) {for
(I=1 i<=nf; i++) {
if (length ($i) > Lengths[i]) lengths[i]=length ($i);
}
rows++;
For (col=1 col<=nf; col++) {
data[rows, col]= $col;
}
}} End {for
(I=1; i<=length (lengths); i++) {
lengths[i]=lengths[i]+4;
}
For (I=1 i<=rows; i++) {
print format (data[i, 1], lengths[1]), Format (Data[i, 2], lengths[2], "right"), Format (DA Ta[i, 3], lengths[3], "right"), Format (Data[i, 4], lengths[4], "right"), Format (Data[i, 5, lengths[5])
}
The first is a format function that is used to format some strings that contain three parameters: the first argument value is a string that needs to be formatted, the second argument is a string that needs to be formatted as long, and the third parameter is used to indicate that when the string length is less than MaxLen, Fill in the front or back space.
Next is the Begin section, which defines two variables, and rows is used to indicate how many lines of text content have to be processed, and there are no NR variables taken into account because of the empty line problem; cols is used to define the number of columns that will eventually need to be displayed, so it is defined as 5.
The action section, which handles the row where the column is 5, here according to the need to write their own filter conditions, in the above example in order to not do too much filtering; This section uses two loops: the first loop is used to calculate the maximum length of each column in the row and saves it in the lengths array The second loop is to put the required data into a two-dimensional array;
Finally, the end section, which includes two loops: The first loop adds the maximum length of each column to 4, in order to add some spacing between each column, and the second loop is used to format the output, where the Name,designation and department Liezo are aligned, The number column is right-aligned.
Test and run the awk-f Test.awk test.txt command at the command line, you can get the following results
ID Name designation Department Salary
Thomas Manager Sales $5,000
Jason Developer Technology $5,500
Sanjay Sysadmin Technology $7,000 Nisha Manager Marketing $9,500
Randy DBA Technology $6,000