用shell脚本实现,读取txt内容输出为带边框的表格样式,表格中含三列内容
时间: 2024-04-30 09:17:22 浏览: 15
好的,可以为您提供一个shell脚本,实现读取txt内容并输出为带边框的表格样式,表格中含三列内容。以下是脚本代码:
```shell
#!/bin/bash
# 读取txt文件
input_file='input.txt'
# 表格分隔线,便于设置表格宽度
delimiter='+---------------+---------------+---------------+'
# 打印表头
echo $delimiter
echo "| Column 1 | Column 2 | Column 3 |"
echo $delimiter
# 读取每一行信息
while read line; do
# 解析每一列信息
col1=$(echo $line | awk '{print $1}')
col2=$(echo $line | awk '{print $2}')
col3=$(echo $line | awk '{print $3}')
# 打印每一行信息
echo "| $col1 | $col2 | $col3 |"
echo $delimiter
done < $input_file
```
请将上述代码复制到您的shell脚本文件中,并将`input.txt`替换为您所需读取的txt文件名。同时,您也可以修改表格的列数、列宽等参数,以满足您的具体需求。
相关问题
用shell脚本实现,读取txt内容输出为带边框的表格样式,表格中含三列内容,并固定每列宽度
好的,我知道了您的问题,让我来为您回答。
您可以使用以下的 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` 改为您要读取的文件名即可。这个脚本会将每个空格分隔的单词解析成一行的三个部分,并在每列的两侧添加 | 符号,之后就可以输出带边框的表格了。
shell脚本读取数据库表格内容
要在shell脚本中读取数据库表格内容,需要使用命令行工具如mysql或sqlite。以下是一个使用mysql的示例脚本:
```
#!/bin/bash
# 连接数据库
mysql -u username -p password -h hostname -D dbname << EOF
# 查询表格内容
SELECT * FROM tablename;
EOF
```
在此示例中,需要将“username”、“password”、“hostname”、“dbname”和“tablename”替换为实际的数据库连接信息和表格名称。脚本会连接到数据库并查询表格内容,然后将结果输出到终端。可以将输出保存到文件中,或者使用其他命令对结果进行处理。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)