bash - 在 BASH 中分两列输出一个文件

标签 bash

我想在第 n 行之后将文件重新排列成两列。

例如,假设我这里有一个这样的文件:

This is a bunch
of text
that I'd like to print
as two
columns starting
at line number 7
and separated by four spaces.
Here are some
more lines so I can
demonstrate
what I'm talking about.

我想像这样打印出来:

This is a bunch           and separated by four spaces.
of text                   Here are some
that I'd like to print    more lines so I can
as two                    demonstrate
columns starting          what I'm talking about.
at line number 7

我如何使用 bash 命令或函数来做到这一点?

最佳答案

实际上,pr 几乎可以做到这一点:

pr --output-tabs=' 1' -2 -t tmp1 

This is a bunch                     and separated by four spaces.
of text                             Here are some
that I'd like to print              more lines so I can
as two                              demonstrate
columns starting                    what I'm talking about.
at line number 7  

-2 两列; -t 省略页眉;如果没有 --output-tabs=' 1',它会为它添加的每 8 个空格插入一个制表符。您还可以设置页面宽度和长度(如果您的实际文件长于 100 行);查看 man pr 以获得一些选项。

如果您确定“比左边最长的一行多四个空格”,那么您可能需要使用更复杂的东西;

以下内容适用于您的测试输入,但已到达正确答案应该是“已经使用 Perl;”的地步;

#!/bin/sh
infile=${1:-tmp1}
longest=$(longest=0;
          head -n $(( $( wc -l $infile | cut -d ' ' -f 1 ) / 2 )) $infile | \
              while read line
              do
                  current="$( echo $line | wc -c | cut -d ' ' -f 1 )"
                  if [ $current -gt $longest ]
                  then
                      echo $current
                      longest=$current
                  fi
              done | tail -n 1 )
pr -t -2 -w$(( $longest * 2 + 6 )) --output-tabs=' 1' $infile

This is a bunch           and separated by four spa
of text                   Here are some
that I'd like to print    more lines so I can
as two                    demonstrate
columns starting          what I'm talking about.
at line number 7          

... 重新阅读您的问题,我想知道您的意思是不是要从字面上指定程序的第 nth 行,在这种情况下,除非该行发生,否则以上都不会起作用半途而废。

关于bash - 在 BASH 中分两列输出一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30744258/

相关文章:

json - jq:将对象数组转换为对象

bash - 在 Ubuntu 18.04 上使用 bash 编写 "sudo apt upgrade"脚本时,如何自动绕过 "package configuration"屏幕?

bash - 为什么 `ack` 像这样与 `bash` 一起使用时不产生输出?

linux - 监控没有第 3 方包的目录变化

git - 在 Windows 上为 Git 配置 GPG

bash - 如何通过golang获取环境变量PS1?

c - 在 c 中访问 bash 局部变量

bash - 如何在 bash 中从 .rar 中提取单个文件

bash - 文件中的列字符串版本,bash sed awk

bash - 使用 bash 自动回答 Graphite 安装的 django sync 提示