我有这个表结构(假设分隔符是制表符):
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格式化之后,我尝试使用fmt
和fold
(这基本上只是将标题放到表格中),但它们当然不反映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
你可以尝试Perl one-liner
perl -lpe ' s/(.{20,}?)\s/$1\n\t /g ' file
给定的输入
$ cat thurse.txt
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
$ perl -lpe ' s/(.{20,}?)\s/$1\n\t /g ' thurse.txt
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
$
如果你想尝试30/40/50的长度窗口
$ perl -lpe ' s/(.{30,}?)\s/$1\n\t /g ' thurse.txt
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
$ perl -lpe ' s/(.{40,}?)\s/$1\n\t /g ' thurse.txt
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
$ perl -lpe ' s/(.{50,}?)\s/$1\n\t /g ' thurse.txt
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
$