简体   繁体   English

计算字符串中出现的次数。 的Linux

[英]Count the number of occurrences in a string. Linux

Okay so what I am trying to figure out is how do I count the number of periods in a string and then cut everything up to that point but minus 2. Meaning like this: 好的,所以我想弄清楚的是如何计算字符串中的句点数,然后将所有内容减到该点,但减去负2。这样的意思是:

string="aaa.bbb.ccc.ddd.google.com"

number_of_periods="5"

number_of_periods=`expr $number_of_periods-2`

string=`echo $string | cut -d"." -f$number_of_periods`

echo $string

result: "aaa.bbb.ccc.ddd"

The way that I was thinking of doing it was sending the string to a text file and then just greping for the number of times like this: 我想到的方式是将字符串发送到文本文件,然后像这样反复几次:

 grep -c "." infile

The reason I don't want to do that is because I want to avoid creating another text file for I do not have permission to do so. 我不想这样做的原因是因为我不想创建另一个文本文件,因为我没有这样做的权限。 It would also be simpler for the code I am trying to build right now. 我现在尝试构建的代码也将更加简单。

EDIT 编辑

I don't think I made it clear but I want to make finding the number of periods more dynamic because the address I will be looking at will change as the script moves forward. 我想我没有说清楚,但是我想使周期数更加动态,因为随着脚本的前进,我将要查找的地址将发生变化。

If you don't need to count the dots, but just remove the penultimate dot and everything afterwards, you can use Bash's built-in string manuipulation . 如果您不需要计算点数,只需要删除倒数第二个点,然后再删除所有内容,则可以使用Bash内置的字符串处理方法

${string%substring} Deletes shortest match of $substring from back of $string . ${string%substring}$string 后面删除$substring最短匹配项。

Example: 例:

$ string="aaa.bbb.ccc.ddd.google.com"
$ echo ${string%.*.*} 
aaa.bbb.ccc.ddd

Nice and simple and no need for sed , awk or cut ! 美观而简单,无需sedawkcut

What about this: 那这个呢:

echo "aaa.bbb.ccc.ddd.google.com"|awk 'BEGIN{FS=OFS="."}{NF=NF-2}1'

(further shortened by helpful comment from @steve) (通过@steve的有用评论进一步缩短)

gives: 给出:

aaa.bbb.ccc.ddd

The awk command: awk命令:

    awk 'BEGIN{FS=OFS="."}{NF=NF-2}1'

works by separating the input line into fields ( FS ) by . 通过将输入行分隔为字段( FS )来工作. , then joining them as output ( OFS ) with . ,然后将它们作为输出( OFS )加入. , but the number of fields ( NF ) has been reduced by 2. The final 1 in the command is responsible for the print. ,但字段数( NF )减少了2。命令中的最后1负责打印。

This will reduce a given input line by eliminating the last two period separated items. 通过消除最后两个句点分隔的项,这将减少给定的输入行。

This approach is " shell-agnostic " :) 这种方法是“ 不可知的 ” :)

Perhaps this will help: 也许这会有所帮助:

#!/bin/sh

input="aaa.bbb.ccc.ddd.google.com"

number_of_fields=$(echo $input | tr "." "\n" | wc -l)
interesting_fields=$(($number_of_fields-2))

echo $input | cut -d. -f-${interesting_fields}
grep -o "\." <<<"aaa.bbb.ccc.ddd.google.com" | wc -l
5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM