用shell脚本实现,读取txt内容输出为带边框的表格样式,表格中含三列内容,并固定每列宽度
时间: 2024-05-11 21:17:00 浏览: 2
好的,我知道了您的问题,让我来为您回答。
您可以使用以下的 Shell 脚本代码来实现读取 txt 内容并输出带边框的表格样式,表格中含三列内容,并固定每列宽度的功能:
```
#!/bin/bash
# Define the width of each column
col1_width=20
col2_width=30
col3_width=50
# Read the file contents to a variable
file_contents="$(cat yourfile.txt)"
# Parse the file contents line by line and create a table
for line in $file_contents; do
# Split the line into three columns
col1="$(echo $line | cut -d' ' -f1)"
col2="$(echo $line | cut -d' ' -f2)"
col3="$(echo $line | cut -d' ' -f3-)"
# Print the table row with borders
printf "| %-*s | %-*s | %-*s |\n" \
$col1_width "$col1" \
$col2_width "$col2" \
$col3_width "$col3"
done
# Print the table header and footer with borders
printf "+-%-*s-+-%-*s-+-%-*s-+\n" \
$col1_width "--------------------" \
$col2_width "------------------------------" \
$col3_width "------------------------------------------------"
```
您只需要将代码中的 `yourfile.txt` 改为您要读取的文件名即可。这个脚本会将每个空格分隔的单词解析成一行的三个部分,并在每列的两侧添加 | 符号,之后就可以输出带边框的表格了。