我正在学习bash脚本,但是我试图编写一个脚本来解决问题,但是不能。
样本测试案例:
Input:
StoreId,Name,Type,Revenue,StoreExpenses (this line is not provided as cmd line argument)
1,RockDeptStore,stationary,100,50
2,WembleyStore,departmental,85,81
3,HealthyStore,grocery,95,97
4,Ministore,medical,60,55
Output:
1|RockDeptStore|stationary|100|50|50
4|Ministore|medical|60|55|5
2|WembleyStore|departmental|85|81|4
script.sh:
#!/bin/bash
#inputs
for record in "$@"
do
revenue=$(cut -d ',' -f 4 <<< $record)
expenses=$(cut -d ',' -f 5 <<< $record)
((profit=revenue-expenses))
if [[ profit -gt 0 ]]
then
# how to update this record with '|' and where to store this record so that I can access it later in my script for sorting.
fi
done
我需要编写一个shell-script script.sh
,它将每个商店详细信息的输入作为命令行参数。
我需要打印所有带有附加字段profit = Revenue - StoreExpenses
的商店,并且需要将分隔符从“,”更改为“ |”。
并仅按其各自的profit
的降序打印那些具有profit > 0
的商店,如上面的示例输出所示。
我们将script.sh
运行为:
./script.sh 1,RockDeptStore,stationary,100,50 2,WembleyStore,departmental,85,81 3,HealthyStore,grocery,95,97 4,Ministore,medical,60,55
分析解答
您可以使用字符串替换来替换每行中的所有逗号
模式为:${parameter//pattern/string}
参见子串替换在此链接
所以在您的情况下,${record//,/|}
然后,您可以将利润大于0的每次迭代保存到变量中,并在最后添加利润列。您可以使用相同的变量,并每次都添加一个换行符。
最后,sort
的线。
-r
选项使排序反向。
-t
和-k
选项一起工作以在每行中查找第六个项目,其中的项目由|
分隔,并进行相应的排序。
因此,一切看起来可能像这样:
#!/bin/bash
result=''
newline=$'\n'
#inputs
for record in "$@"
do
revenue=$(cut -d ',' -f 4 <<< $record)
expenses=$(cut -d ',' -f 5 <<< $record)
((profit=revenue-expenses))
if [[ profit -gt 0 ]]
then
newRecord=${record//,/|}
result+="${newRecord}|${profit}${newline}"
fi
done
sorted=$(sort -rt'|' -k6 <<< ${result})
printf "${sorted}"
我必须对您的脚本进行一些其他更改才能使其对我有用:
gt
->-gt
- 将
<<< ${record}
添加到cut命令