String 按行将列彼此对齐
假设文件包含三列字符串String 按行将列彼此对齐,string,bash,text-alignment,String,Bash,Text Alignment,假设文件包含三列字符串 > cat file foo foo bar bar baz baz qux qux bash中的什么命令(如果有的话)可以用来按行对齐这些列?正确的输出如下所示: > sought_command file foo foo bar bar baz baz qux qux 使用awk: $ awk 'max<NF{max=NF} # Get max number of columns { #For every input line,
> cat file
foo foo bar
bar baz
baz qux
qux
bash中的什么命令(如果有的话)可以用来按行对齐这些列?正确的输出如下所示:
> sought_command file
foo foo
bar bar
baz baz
qux qux
使用awk:
$ awk 'max<NF{max=NF} # Get max number of columns
{ #For every input line,
for(i=1;i<=NF;i++){
b[$i]++; # Record all possible tokens, like foo, bar etc.
a[i$i]++; # Record their column indices
}
}
END{
for(i in b) #Get max length of all the tokens (for printing)
if(c<length(i))
c=length(i);
for(i in b) # For each token,
{
for(j=1;j<=max;j++){ # For every column,
if(a[j i]) d = i; # Decide, if we want to print it, or left blank...
else d="";
printf "%-"(c+5)"s", d; # Print the token, or blank space
}
print ""; # Print newline after every tokens line.
}
}' test.input
foo foo
baz baz
qux qux
bar bar
可以维持标记首次出现的顺序。e、 在上面(重新排序)的情况下,它将是foo、bar、baz、qux
$ awk 'max<NF{max=NF} # Get max number of columns
{ #For every input line,
for(i=1;i<=NF;i++){
if(!b[$i]++)
token[j++]=$i;
a[i$i]++; # Record their column indices
}
}
END{
for(i in b) #Get max length of all the tokens (for printing)
if(max_len<length(i))
max_len=length(i);
PROCINFO["sorted_in"] = "@ind_num_asc";
for(i in token) { # For each token,
for(j=1;j<=max;j++){ # For every column,
if(a[j token[i]]) d = token[i]; # Decide, if we want to print it, or left blank...
else d="";
printf "%-"(max_len+5)"s", d; # Print the token, or blank space
}
print ""; # Print newline after every tokens line.
}
}' test.input.reordered
foo foo
bar bar
baz baz
qux qux
$awk'max如果同一列中出现两个相同的单词怎么办?为什么在条形码
的情况下会有额外的空间?@anishsane我想OP想要的是在保留“列”的同时将相同的单词放在同一行。^^^哦,现在明白了…@anishsane用户4ae1e1是正确的。我要找的是这样一种代码,它将列对齐,使每一行最终包含相同的单词,但保持列。哇!它按预期工作。这是一些密集的awk代码。我向你脱帽致敬!仔细查看您的代码,我注意到行的原始顺序没有得到维护。按照这个顺序,第二行应该是“bar”而不是“baz”。维护原始顺序需要什么?如果代码的输出保存为variable out,则以下代码将重新建立原始行顺序:for i in$(awk'{print$1}'文件);做grep^$i输出;完成
没有原始的行顺序,因为原始数据只是一个模式。请参见编辑。
$ awk 'max<NF{max=NF} # Get max number of columns
{ #For every input line,
for(i=1;i<=NF;i++){
if(!b[$i]++)
token[j++]=$i;
a[i$i]++; # Record their column indices
}
}
END{
for(i in b) #Get max length of all the tokens (for printing)
if(max_len<length(i))
max_len=length(i);
PROCINFO["sorted_in"] = "@ind_num_asc";
for(i in token) { # For each token,
for(j=1;j<=max;j++){ # For every column,
if(a[j token[i]]) d = token[i]; # Decide, if we want to print it, or left blank...
else d="";
printf "%-"(max_len+5)"s", d; # Print the token, or blank space
}
print ""; # Print newline after every tokens line.
}
}' test.input.reordered
foo foo
bar bar
baz baz
qux qux