【问题标题】:How to write the script to implement the below logic?如何编写脚本来实现以下逻辑?
【发布时间】:2020-12-04 00:03:25
【问题描述】:

我正在学习 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 &gt; 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

【问题讨论】:

  • “正在尝试编写脚本”。请展示您的尝试,描述您遇到的问题,并提出一个有助于您推进尝试的具体问题。不要只要求完整的代码。
  • 好的,我已经包含了我正在编写的脚本script.sh,但是卡在了中间。

标签: linux bash shell scripting sh


【解决方案1】:

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

模式为:${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
  • 在剪切命令中添加了&lt;&lt;&lt; ${record}

【讨论】:

  • @William_Mizzi。你使用“这里的字符串”来提供标准输入来剪切和排序命令,我们有什么替代方法吗?
  • 为什么我们必须在newline=$'\n' 中包含$
  • 您使用 'here strings' 来提供标准输入来剪切和排序命令,我们有什么替代方法吗?为什么我们必须在 newline=$'\n' 中包含 $
【解决方案2】:

您可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 2022-12-15
    • 1970-01-01
    相关资源
    最近更新 更多