gpt4 book ai didi

linux - Bash Shell 编程将文本文件中的变量存储到数组中

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:31:07 28 4
gpt4 key购买 nike

我的程序应该能够以这种方式工作。

下面是名为 BookDB.txt 的文本文件的内容个人由冒号 (:) 分隔,文本文件中的每一行都应作为一组信息,并按如下所述的顺序排列。

标题:作者:价格:可用数量:售出数量

Harry Potter - The Half Blood Prince:J.K Rowling:40.30:10:50
The little Red Riding Hood:Dan Lin:40.80:20:10
Harry Potter - The Phoniex:J.K Rowling:50.00:30:20
Harry Potter - The Deathly Hollow:Dan Lin:55.00:33:790
Little Prince:The Prince:15.00:188:9
Lord of The Ring:Johnny Dept:56.80:100:38

我真的打算1)逐行读取文件,存入数​​组2)显示出来

但是我什至不知道如何开始第一个。通过网上研究,以下是我到目前为止编写的代码。

#!/bin/bash

function fnReadFile()
{
while read inputline
do
bTitle="$(echo $inputline | cut -d: -f1)"
bAuthor="$(echo $inputline | cut -d: -f2)"
bPrice="$(echo $inputline | cut -d: -f3)"
bQtyAvail="$(echo $inputline | cut -d: -f4)"
bQtySold="$(echo $inputline | cut -d: -f5)"
bookArray[Count]=('$bTitle', '$bAuthor', '$bPrice', '$bQtyAvail', '$bQtySold')
Count = Count + 1
done
}

function fnInventorySummaryReport()
{
fnReadFile
echo "Title Author Price Qty Avail. Qty Sold Total Sales"
for t in "${bookArray[@]}"
do
echo $t
done
echo "Done!"
}

if ! [ -f BookDB.txt ] ; then #check existance of bookdb file, create the file if not exist else continue
touch BookDB.txt
fi

"HERE IT WILL THEN BE THE MENU AND CALLING OF THE FUNCTION"

提前感谢那些提供帮助的人!

最佳答案

为什么要将整个内容读入数组?需要信息时查询文件:

#!/bin/sh# untested code:# print the values of any line that match the pattern given in $1grep "$1" BookDB.txt |while IFS=: read  Title Author Price QtyAvailable QtySold; do  echo title = $Title  echo author = $Authordone

除非您的文本文件非常大,否则您不太可能需要数组中的数据。如果它足够大,您出于性能原因需要它,那么您真的不应该在 sh 中对此进行编码。

关于linux - Bash Shell 编程将文本文件中的变量存储到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9003673/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com