首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当字符串后面的数字大于某个数字时,请打印下2行

当字符串后面的数字大于某个数字时,请打印下2行
EN

Stack Overflow用户
提问于 2018-11-09 01:16:32
回答 3查看 200关注 0票数 0

让我们说我们

  • 如果我每小时挣8美元
  • 我会用它当食物
  • 和租金
  • 如果我每小时挣10美元,
  • 我会用它来吃,租
  • 和气体
  • 如果我一小时挣12美元,
  • 我会用它当食物
  • 和学费“

如果"make“一词后面的数字大于9,我想打印出下一行。在我的情况下,答案是:-我会用它做食物、房租和汽油--我会用它做食物--有人能帮我吗?

EN

回答 3

Stack Overflow用户

发布于 2018-11-09 02:19:01

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

代码语言:javascript
复制
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这样的一条线来做了。

代码语言:javascript
复制
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

我们所做的就是

代码语言:javascript
复制
for i in `echo $text | tr "\n" "-" | sed 's,if i make,\;,g'`

用“如果我做了”来分割字符串,然后循环遍历并执行

代码语言:javascript
复制
line=`echo "$i" | sed 's,^[ \t],,g'`

移除任何尾随空间

代码语言:javascript
复制
num=`echo $line | awk -F ' ' '{print $1}'`

从线上得到号码,然后

代码语言:javascript
复制
if [[ $num -gt 9 ]];then printf '%s' $(echo $line | awk -F 'hour,-' '{print $2}');fi

如果数字大于9,打印“小时”之后的内容,-

票数 1
EN

Stack Overflow用户

发布于 2018-11-09 02:11:58

基本上,您想检查字符串并在make之后得到数字。你要做的是拥有String message = "If I make 100..."然后你会说

代码语言:javascript
复制
//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]);

现在,hourly_pay将是单词"make“后面的数字。因此,您现在所要做的就是检查它是否大于9,例如:

代码语言:javascript
复制
if(hourly_pay > 9){
    //Print whatever you want.
}else{
    //Whatever. 
}
票数 0
EN

Stack Overflow用户

发布于 2018-11-09 05:44:29

使用Perl一行程序

代码语言:javascript
复制
$ 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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53218463

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档