简体   繁体   中英

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:

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 .

${string%substring} Deletes shortest match of $substring from back of $string .

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 !

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)

gives:

aaa.bbb.ccc.ddd

The awk command:

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

works by separating the input line into fields ( FS ) by . , then joining them as output ( OFS ) with . , but the number of fields ( NF ) has been reduced by 2. The final 1 in the command is responsible for the print.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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