我想编写一个脚本来执行以下操作
while not end of file
read line
print columns 1 to o-1 with | as delimiter
print column o
print columns o+1 to n with | as delimiter
end loop
我怎样才能做到这一点?
假设每一行只是一个空格分隔字段的列表:
o=7 # or whatever o should be
while read -r -a columns; do
( IFS="|"
printf "${columns[*]:0:o-1}\n"
printf "${columns[o-1]}\n"
printf "${columns[*]:o}\n"
)
done
read -a将该行读入一个名为columns. 我把printfs 放在一个子shell中,这样我们就不用担心IFS以后恢复 s 的值了。语法"${array[*]:x:y}"表示要创建一个由 from 的y字段组成的字符串array,以 field 开头x,使用第一个字符 of$IFS分隔字符串中的每个字段。
如果您的字段是制表符分隔的,则以下一行脚本可以打印带有单元格边框的表格
sed -e 's/\t/_|/g' table.txt | column -t -s '_' | awk '1;!(NR%1){print "-----------------------------------------------------------------------";}'
Description |value |Comment
-----------------------------------------------------------------------
Internal |322 |
-----------------------------------------------------------------------
External |42515 |
-----------------------------------------------------------------------
对于上述 sed 命令上的空格更改 \t 以外的分隔符。