使用awk
. 块中有一个硬编码变量 ( columns_to_delete
)BEGIN
来指示要删除的字段的位置。然后脚本将计算每个字段的宽度,并删除与变量位置匹配的字段。
假设infile
有问题的内容和以下内容script.awk
:
BEGIN {
## Hard-coded positions of fields to delete. Separate them with spaces.
columns_to_delete = "5 8 11"
## Save positions in an array to handle it better.
split( columns_to_delete, arr_columns )
}
## Process header.
FNR == 1 {
## Split header with a space followed by any non-space character.
split( $0, h, /([[:space:]])([^[:space:]])/, seps )
## Use FIELDWIDTHS to handle fixed format of data. Set that variable with
## length of each field, taking into account spaces.
for ( i = 1; i <= length( h ); i++ ) {
len = length( h[i] seps[i] )
FIELDWIDTHS = FIELDWIDTHS " " (i == 1 ? --len : i == length( h ) ? ++len : len)
}
## Re-calculate fields with new FIELDWIDTHS variable.
$0 = $0
}
## Process header too, and every line with data.
{
## Flag to know if 'p'rint to output a field.
p = 1
## Go throught all fields, if found in the array of columns to delete, reset
## the 'print' flag.
for ( i = 1; i <= NF; i++ ) {
for ( j = 1; j <= length( arr_columns ); j++ ) {
if ( i == arr_columns[j] ) {
p = 0
break
}
}
## Check 'print' flag and print if set.
if ( p ) {
printf "%s", $i
}
else {
printf " "
}
p = 1
}
printf "\n"
}
像这样运行它:
awk -f script.awk infile
具有以下输出:
id quantity colour shape colour shape colour shape
1 10 blue square red triangle pink circle
2 12 yellow pentagon orange rectangle purple oval
编辑:哦哦,刚刚意识到输出不正确,因为两个字段之间存在连接。修复这将是太多的工作,因为在开始处理任何内容之前将检查每一行的最大列大小。但是有了这个脚本,我希望你能明白。现在不是时候,也许我可以稍后尝试修复它,但不确定。
编辑 2:固定为删除的每个字段添加额外的空间。这比预期的要容易:-)
编辑3:见评论。
我已经修改了该BEGIN
块以检查是否提供了一个额外的变量作为参数。
BEGIN {
## Check if a variable 'delete_col' has been provided as argument.
if ( ! delete_col ) {
printf "%s\n", "Usage: awk -v delete_col=\"column_name\" -f script.awk " ARGV[1]
exit 0
}
}
并添加到FNR == 1
模式计算要删除的列数的过程:
## Process header.
FNR == 1 {
## Find column position to delete given the name provided as argument.
for ( i = 1; i <= NF; i++ ) {
if ( $i == delete_col ) {
columns_to_delete = columns_to_delete " " i
}
}
## Save positions in an array to handle it better.
split( columns_to_delete, arr_columns )
## ...
## No modifications from here until the end. Same code as in the original script.
## ...
}
现在像这样运行它:
awk -v delete_col="size" -f script.awk infile
结果将是相同的。