如何编写脚本来实现以下逻辑?

时间:2020-08-14 05:23:27

标签: linux bash shell scripting sh

我正在学习 bash脚本,并且我试图编写一个脚本来解决问题,但是不能。

示例测试用例:

输入

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

输出

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.sh,它将每个商店详细信息的输入作为命令行参数

我需要使用其他字段 profit = Revenue - StoreExpenses打印所有商店,并且需要将分隔符从','更改为'|'。

并仅打印其各自profit > 0降序profit的商店,如上面的示例输出所示。

我们以以下方式运行script.sh

./script.sh 1,RockDeptStore,stationary,100,50 2,WembleyStore,departmental,85,81 3,HealthyStore,grocery,95,97 4,Ministore,medical,60,55

2 个答案:

答案 0 :(得分:2)

您可以使用字符串替换来替换每行中的所有逗号

模式为:${parameter//pattern/string} 请参见子字符串替换at this link

因此,根据您的情况,${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}

答案 1 :(得分:0)

您可以使用sort实用程序对输出进行排序。

#!/usr/bin/env bash

for element; do
  IFS=, read -r _ _ _ revenue store_expenses <<< "$element"
  profit=$(( revenue - store_expenses ))
  if (( profit > 0 )); then
    output=${element//,/|}
    printf '%s|%s\n' "$output" "$profit"
  fi
done | sort -rt'|' -k 6

您可以使用参数运行脚本。

./script.sh 1,RockDeptStore,stationary,100,50 2,WembleyStore,departmental,85,81 3,HealthyStore,grocery,95,97 4,Ministore,medical,60,55