The shell script implementation finds the last occurrence of a character in a string _linux shell

Source: Internet
Author: User

You need to find the last position of one of the characters in the string, which is available in PHP (Strrpos) or Perl (Rindex), and you can't think of a way out of the shell. Post on the Forum also no one answer (do not know whether the problem is too simple or really very advanced ...) )。

Because the matter is not urgent, so help college students. Pacman is worthy of a master, 32 next to wake up in the dream of people:

Rindex.sh Code:

Copy Code code as follows:

#!/bin/bash

strtocheck=$1;
chartosearch=$2;

Let pos= ' echo ' $strToCheck | Awk-f ' $charToSearch ' ' {printf '%d ', Length ($)-length ($NF)} '

echo "Char $charToSearch Lastpos is: $pos"


Use examples:
Copy Code code as follows:

[zeal]$ sh rindex.sh www.zeali.net.
Char. Lastpos is:10

Calfen provides a more self-reliant way: He wrote a small program in C to achieve rindex function, gcc rindex.c-o rindex after the shell has a can be invoked rindex:)
RINDEX.C Code:

Copy Code code as follows:

#include <strings.h>
int main (int argc, char *argv[]) {
char* Wholeword;
Char Subchar;
char* Subword;

int ret;

if (argc!=3) {
printf ("Use:rindex word char\n");
Exit (0);
}
WHOLEWORD=ARGV[1];
SUBCHAR=*ARGV[2];
Subword=rindex (Wholeword,subchar);

if (0 = subword)
ret = 0;
Else
ret = (subword-wholeword+1);
printf ("%d\n", ret);
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.