如何将多行更改为一列
How to change many row to column
我有一个文件如下,当找到一个特定的行(这里是del_size fq
)时,我想更改为列。
$ cat file.txt
del_size fq
0 13452
-1 13034
del_size fq
0 13
-1 0
-2 2155
del_size fq
0 6600
-1 8
-2 0
非常感谢任何帮助。
谢谢
复杂的GNU awk
解决方案:
awk '{
if (/^del_size/) {
h = (h? h OFS : "") [=10=]; cnt++;
if (r_cnt > max_rows) max_rows = r_cnt;
i = j = r_cnt = 0
}
else {
arr[cnt][++i] = [=10=];
r_cnt++
}
next
}
END{
print h;
for (i = 1; i <= max_rows; i++) {
for (j = 1; j <= cnt; j++) {
items = arr[j][i];
if (items == "") items = "" OFS "";
printf "%s%s", (j == 1 ? "" : OFS), items
}
print ""
}
}' OFS='\t' file
输出:
del_size fq del_size fq del_size fq
0 13452 0 13 0 6600
-1 13034 -1 0 -1 8
-2 2155 -2 0
这将在任何 UNIX 机器上使用任何 shell 中的任何 awk 生成制表符分隔的输出,然后您可以将其通过管道传输到列或导入到 Excel 或之后您需要做的任何事情:
$ cat tst.awk
BEGIN { OFS="\t" }
/^del_size/ { ++numCols; rowNr=0 }
{ = }
NR==1 {
empty = [=10=]
gsub(/[^[:space:]]+/,"",empty)
}
{
cell[++rowNr,numCols] = [=10=]
numRows = (rowNr > numRows ? rowNr : numRows)
}
END {
for (rowNr=1; rowNr<=numRows; rowNr++) {
for (colNr=1; colNr<=numCols; colNr++) {
val = ((rowNr,colNr) in cell ? cell[rowNr,colNr] : empty)
printf "%s%s", val, (colNr<numCols ? OFS : ORS)
}
}
}
$ awk -f tst.awk file | column -s$'\t' -t
del_size fq del_size fq del_size fq
0 13452 0 13 0 6600
-1 13034 -1 0 -1 8
-2 2155 -2 0
我有一个文件如下,当找到一个特定的行(这里是del_size fq
)时,我想更改为列。
$ cat file.txt
del_size fq
0 13452
-1 13034
del_size fq
0 13
-1 0
-2 2155
del_size fq
0 6600
-1 8
-2 0
非常感谢任何帮助。 谢谢
复杂的GNU awk
解决方案:
awk '{
if (/^del_size/) {
h = (h? h OFS : "") [=10=]; cnt++;
if (r_cnt > max_rows) max_rows = r_cnt;
i = j = r_cnt = 0
}
else {
arr[cnt][++i] = [=10=];
r_cnt++
}
next
}
END{
print h;
for (i = 1; i <= max_rows; i++) {
for (j = 1; j <= cnt; j++) {
items = arr[j][i];
if (items == "") items = "" OFS "";
printf "%s%s", (j == 1 ? "" : OFS), items
}
print ""
}
}' OFS='\t' file
输出:
del_size fq del_size fq del_size fq
0 13452 0 13 0 6600
-1 13034 -1 0 -1 8
-2 2155 -2 0
这将在任何 UNIX 机器上使用任何 shell 中的任何 awk 生成制表符分隔的输出,然后您可以将其通过管道传输到列或导入到 Excel 或之后您需要做的任何事情:
$ cat tst.awk
BEGIN { OFS="\t" }
/^del_size/ { ++numCols; rowNr=0 }
{ = }
NR==1 {
empty = [=10=]
gsub(/[^[:space:]]+/,"",empty)
}
{
cell[++rowNr,numCols] = [=10=]
numRows = (rowNr > numRows ? rowNr : numRows)
}
END {
for (rowNr=1; rowNr<=numRows; rowNr++) {
for (colNr=1; colNr<=numCols; colNr++) {
val = ((rowNr,colNr) in cell ? cell[rowNr,colNr] : empty)
printf "%s%s", val, (colNr<numCols ? OFS : ORS)
}
}
}
$ awk -f tst.awk file | column -s$'\t' -t
del_size fq del_size fq del_size fq
0 13452 0 13 0 6600
-1 13034 -1 0 -1 8
-2 2155 -2 0