gpt4 book ai didi

bash - 用 awk/bash 包装一个超大列( pretty-print )

转载 作者:行者123 更新时间:2023-12-02 00:22:05 30 4
gpt4 key购买 nike

我有这个表结构(假设分隔符是制表符):

AAA  BBBB  CCC
01 Item Description here
02 Meti A very very veeeery long description which will easily extend the recommended output width of 80 characters.
03 Etim Last description

我想要的是:

AAA  BBBB  CCC
01 Item Description here
02 Meti A very very veeeery
long description which
will easily extend the
recommended output width
of 80 characters.
03 Etim Last description

这意味着我想将 $3 拆分为具有预定义 WIDTH 的字符串数组,其中第一个元素“正常”附加到当前行和所有后续元素根据前两列的填充得到一个新的线宽标识(如果这样更容易,填充也可以固定)。

或者,$0 中的文本可以按 GLOBAL_WIDTH(例如 80 个字符)拆分为第一个字符串和“rest” -> 第一个字符串“正常”打印使用 printf,其余部分由 GLOBAL_WIDTH - (COLPAD1 + COLPAD2) 拆分,并如上所述附加宽度新行。

我尝试在我的 awk 格式化后使用 fmtfold (这基本上只是将标题放在表格中),但它们当然不反射(reflect) awk 的字段感知.

我如何使用 bash 工具和/或 awk 实现这一点?

最佳答案

首先构建一个测试文件(名为file.txt):

echo "AA  BBBB  CCC
01 Item Description here
02 Meti A very very veeeery long description which will easily extend the recommended output width of 80 characters.
03 Etim Last description" > file.txt

现在是脚本(名为 ./split-columns.sh):

#!/bin/bash
FILE=$1

#find position of 3rd column (starting with 'CCC')
padding=`cat $FILE | head -n1 | grep -aob 'CCC' | grep -oE '[0-9]+'`
paddingstr=`printf "%-${padding}s" ' '`

#set max length
maxcolsize=50
maxlen=$(($padding + $maxcolsize))

cat $FILE | while read line; do
#split the line only if it exceeds the desired length
if [[ ${#line} -gt $maxlen ]] ; then
echo "$line" | fmt -s -w$maxcolsize - | head -n1
echo "$line" | fmt -s -w$maxcolsize - | tail -n+2 | sed "s/^/$paddingstr/"
else
echo "$line";
fi;
done;

最后将文件作为一个参数运行它

./split-columns.sh file.txt > fixed-width-file.txt

输出将是:

AA  BBBB  CCC
01 Item Description here
02 Meti A very very veeeery long description
which will easily extend the recommended output
width of 80 characters.
03 Etim Last description

关于bash - 用 awk/bash 包装一个超大列( pretty-print ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55039681/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com