2012-10-20 wcdj
在对表格形式的输出数据进行处理时,column和sort工具大多可以派上用场。
看一个例子:
#/bin/sh
# 2012-10-20 wcdj
file=test.txt
cat << gerry_here_doc
=================================
usage:
# m: the number of fields from one
cat file | sort +(m-1) -m +(m-1) -m
# useful for pretty-printing displays
# -s option is specifing a set of characters to be used to delimit columns for the -t option
cat file | column -t
=================================
gerry_here_doc
text="
4 20121001-20121018 14523670
1 20121001-20121018 637368
3 20121001-20121018 308371
2 20121001-20121018 14832041
5 20121001-20121018 1.5469409E7
1 20121001-20121017 615608
3 20121001-20121017 305929
5 20121001-20121017 1.5271584E7
4 20121001-20121017 14350047
2 20121001-20121017 14655976
"
echo "$text" > "$file"
echo ""
echo "export file named test.txt to current dir."
echo "the contents of test.txt are: "
cat "$file"
echo "you could find that this file showing looks some confused !"
echo "so, use column command to display it prettily"
echo ""
cat "$file" | column -t
echo ""
echo "then, I wanna sort this file by the second field firstly and the second field next, like this: "
echo ""
cat "$file" | column -t | sort +1 -2 +0 -1
echo ""
echo "test is over"
输出内容如下:
=================================
usage:
# m: the number of fields from one
cat file | sort +(m-1) -m +(m-1) -m
# useful for pretty-printing displays
# -s option is specifing a set of characters to be used to delimit columns for the -t option
cat file | column -t
=================================
export file named test.txt to current dir.
the contents of test.txt are:
4 20121001-20121018 14523670
1 20121001-20121018 637368
3 20121001-20121018 308371
2 20121001-20121018 14832041
5 20121001-20121018 1.5469409E7
1 20121001-20121017 615608
3 20121001-20121017 305929
5 20121001-20121017 1.5271584E7
4 20121001-20121017 14350047
2 20121001-20121017 14655976
you could find that this file showing looks some confused !
so, use column command to display it prettily
4 20121001-20121018 14523670
1 20121001-20121018 637368
3 20121001-20121018 308371
2 20121001-20121018 14832041
5 20121001-20121018 1.5469409E7
1 20121001-20121017 615608
3 20121001-20121017 305929
5 20121001-20121017 1.5271584E7
4 20121001-20121017 14350047
2 20121001-20121017 14655976
then, I wanna sort this file by the second field firstly and the second field next, like this:
1 20121001-20121017 615608
2 20121001-20121017 14655976
3 20121001-20121017 305929
4 20121001-20121017 14350047
5 20121001-20121017 1.5271584E7
1 20121001-20121018 637368
2 20121001-20121018 14832041
3 20121001-20121018 308371
4 20121001-20121018 14523670
5 20121001-20121018 1.5469409E7
test is over
参考:
[1] column http://linux.about.com/library/cmd/blcmdl1_column.htm
[2] sort http://linux.about.com/library/cmd/blcmdl1_sort.htm