Bash 当字符串后面的数字大于某个数字时,打印下两行

Bash 当字符串后面的数字大于某个数字时,打印下两行,bash,shell,unix,Bash,Shell,Unix,假设我们有 如果我每小时挣8美元 我会用它做食物 租金 如果我每小时挣10美元 我会用它来吃饭,租房 煤气 如果我一小时挣12美元 我会用它做食物 及学费“ 如果单词“make”后面的数字大于9,我想打印下一行。 我的答案是: -我会用它来吃饭,租房 -煤气 -我会用它做食物 -学费 有人能帮我吗?你基本上是想检查字符串并在make之后获得数字。你要做的是使用string message=“如果我赚100…”然后你会说 //Divide the string into words by ta

假设我们有

  • 如果我每小时挣8美元
  • 我会用它做食物
  • 租金
  • 如果我每小时挣10美元
  • 我会用它来吃饭,租房
  • 煤气
  • 如果我一小时挣12美元
  • 我会用它做食物
  • 及学费“
如果单词“make”后面的数字大于9,我想打印下一行。 我的答案是: -我会用它来吃饭,租房 -煤气 -我会用它做食物 -学费
有人能帮我吗?

你基本上是想检查字符串并在make之后获得数字。你要做的是使用
string message=“如果我赚100…”
然后你会说

//Divide the string into words by taking out the spaces and then store the words in an array. 
String[] words = message.split(" ");

//All of your numbers were the fourth word so the code below will
//parse the fourth position in the array and make it an integer. 
int hourly_pay = Integer.parseInt(words[3]);
现在,
hourry\u pay
将是单词“make”后的数字。因此,您现在要做的就是检查它是否大于9,如下图所示:

if(hourly_pay > 9){
    //Print whatever you want.
}else{
    //Whatever. 
}

使用Bash,如果将文本放入名为text的变量中

text="if i make 8 dollars an hour
i will use it for food
and rent
if i make 10 dollars an hour,
i will use it for food, rent
and gas
if i make 12 dollars an hour,
i will use it for food
and tuition"
然后你可以像这样用sed和awk在一行中完成它

IFS=";";for i in `echo $text | tr "\n" "-" | sed 's,if i make,\;,g'`;do line=`echo "$i" | sed 's,^[ \t],,g'`; num=`echo $line | awk -F ' ' '{print $1}'`; if [[ $num -gt 9 ]];then printf '%s' $(echo $line | awk -F 'hour,-' '{print $2}');fi;done;echo
我们所做的是

for i in `echo $text | tr "\n" "-" | sed 's,if i make,\;,g'`
用“if i make”拆分字符串,循环遍历并执行

line=`echo "$i" | sed 's,^[ \t],,g'`
然后删除任何尾随空格

num=`echo $line | awk -F ' ' '{print $1}'`
从线路上获取号码,然后

if [[ $num -gt 9 ]];then printf '%s' $(echo $line | awk -F 'hour,-' '{print $2}');fi
如果数字大于9,则使用Perl one liner打印“小时”之后的内容

$ cat > items.txt
if i make 8 dollars an hour
i will use it for food
and rent
if i make 10 dollars an hour,
i will use it for food, rent
and gas
if i make 12 dollars an hour,
i will use it for food
and tuition


$ perl -ne ' { next if  /make ([0-9]+)/ and $x=$1; print if $x > 9 } ' items.txt
i will use it for food, rent
and gas
i will use it for food
and tuition

你能展示一下你的努力/代码吗?