awk可以很简单地做到这一点:
$ cat file.txt
apple
president
example
another
$ awk '{output=""; for(i=1;i<length($0);i++){ output=output" "substr($0,i,2)} print output }' file.txt
ap pp pl le
pr re es si id de en nt
ex xa am mp pl le
an no ot th he er
如果行前的空格是一个问题,您可以通过多种方式处理它,例如在子字符串之前附加一个空格之前检查输出是否为空,或者只是在空格之后提取输出的子字符串,例如
$ awk '{output="";for(i=1;i<length($0);i++){ output=output" "substr($0,i,2)} print substr(output,2) }' file.txt
ap pp pl le
pr re es si id de en nt
ex xa am mp pl le
an no ot th he er
块内的所有内容都{ }针对每一行执行,因为它没有附加条件。
output=""将每一行的输出变量重置为空。
for(i=1;i<length($0);i++){ ... }逐个字符循环遍历每一行的字符串。
output=output" "substr($0,i,2)} print output- 这是在上述循环中执行的。对于字符串的每个字符,输出变量被分配给它的现有值,一个空格,然后是当前索引中的两个字符子字符串 - 遍历每个字符并打印它和下一个字符。