ayr*_*nna 3 solaris sed awk line-editor text-formatting
file1.txt
:
hi
wonderful
amazing
sorry
superman
superhumanwith
loss
Run Code Online (Sandbox Code Playgroud)
file2.txt
:
1
2
3
4
5
6
7
Run Code Online (Sandbox Code Playgroud)
当我尝试使用 paste -d" " file1.txt file2.txt > actualout.txt 进行组合时
actualout.txt
:
hi 1
wonderful 2
amazing 3
sorry 4
superman 5
superhumanwith 6
loss 7
Run Code Online (Sandbox Code Playgroud)
但我希望我的输出看起来像这样
OUT.txt
:
hi 1
wonderful 2
amazing 3
sorry 4
superman 5
superhumanwith 6
loss 7
Run Code Online (Sandbox Code Playgroud)
哪个命令可用于组合 2 个文件,使其看起来像所需的输出?Solaris 5.10 ksh nawk、sed、粘贴
你似乎需要column
:
paste file1.txt file2.txt | column -tc2
Run Code Online (Sandbox Code Playgroud)
创建此输出:
hi 1
wonderful 2
amazing 3
sorry 4
superman 5
superhumanwith 6
loss 7
Run Code Online (Sandbox Code Playgroud)
您当然也可以编写自己的脚本来进行格式化。这是使用的一种方法awk
:
awk '
NR==FNR { a[FNR] = $0 ; if (length > max) max = length ; next }
{ printf "%-*s %s\n", max, a[FNR], $0 }
' file1.txt file2.txt
Run Code Online (Sandbox Code Playgroud)
pr
我可能会选择pr
:
printf %s\\n hi wonderful amazing sorry \
superman superhumanwith loss >/tmp/file
#^what is all of that, anyway?^
seq 7 | pr -tm /tmp/file -
Run Code Online (Sandbox Code Playgroud)
pr
可以像逐列一样-m
逐行合并输入文件(此处/tmp/file
和-
标准输入)paste
,但除此之外它还可以采用许多其他参数。默认情况下,它也会打印页眉和页脚,但-t
会压缩它们。
hi 1
wonderful 2
amazing 3
sorry 4
superman 5
superhumanwith 6
loss 7
Run Code Online (Sandbox Code Playgroud)
expand
如果您有兴趣自己更具体,另一个选择是expand
- 因为您可以向它提供一个虚拟制表位列表,它将扩展到填充它们所需的尽可能多的空格。
seq 7 | paste /tmp/file - | expand -t15
Run Code Online (Sandbox Code Playgroud)
-t
当然,这里我们只需要第一个abstop......
hi 1
wonderful 2
amazing 3
sorry 4
superman 5
superhumanwith 6
loss 7
Run Code Online (Sandbox Code Playgroud)
...但是如果需要更多...
seq 14 | paste /tmp/file - /tmp/file - | expand -t15,23,38,46
Run Code Online (Sandbox Code Playgroud)
...我们可以用逗号分隔的复合列表来拼写它们...
hi 1 hi 2
wonderful 3 wonderful 4
amazing 5 amazing 6
sorry 7 sorry 8
superman 9 superman 10
superhumanwith 11 superhumanwith 12
loss 13 loss 14
Run Code Online (Sandbox Code Playgroud)
grep
:要查找文件中最长行的长度,并且不计算任何尾随空格,并按标准 8 字符制表位位置递增,这可能会起作用:
i=0
while grep -Eq ".{$(((i+=8)-1))}.*[^[:blank:]]" <infile; do :; done
Run Code Online (Sandbox Code Playgroud)
该循环将为$i
每次运行增加 8,并搜索<infile
包含至少与计数的字符数相同的任何行,$i
后跟任何非空白字符。因此,当grep
找不到这样的行时,它将返回 false,并且对于您的示例数据,它将分配:
echo "$i"
16
Run Code Online (Sandbox Code Playgroud)
wc
:但这些都是 POSIX 解决方案。在 GNU 系统上做的最简单的事情是:
wc -L <infile
Run Code Online (Sandbox Code Playgroud)
...列出 中最长行的长度<infile
,但这将包括尾随空格的计数。