我具有此表结构(假设分隔符是制表符):
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实现此目标?
答案 0 :(得分:2)
首先构建一个测试文件(称为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
答案 1 :(得分:1)
您可以尝试Perl单线版
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
$