Position character position in shell string to get character position

Source: Internet
Author: User

Linux shell String Operations (length, find, replace) detailed

The following two string operations are described in this blog post,

1 ${string:p osition}     #在 $string, extract substring 2 ${string starting from position $position :  Position:length}     
View Code

The location of the character/substring in the parent string is required (position), and the shell string does not provide an interface for the location of the substring, and if the operation is based on a string variable, the location of the substring cannot be predicted;

Position of a string within a string using Linux shell script?

The article mentions some solutions that feel valuable and reproduced as follows:

If I has the text in a shell variable, say $a :

a="The cat sat on the mat"

How can I search for "cat" and return 4 using a Linux shell script, or-1 if not found?

1.

With bash

a="The cat sat on the mat"b=catstrindex() {   x="${1%%$2*}"  [[ $x = $1 ]] && echo -1 || echo ${#x}}strindex "$a" "$b"   # prints 4strindex "$a" foo    # prints -1
ShareImprove this answer2.

I used awk for this

a="The cat sat on the mat"test="cat"awk -v a="$a" -v b="$test" ‘BEGIN{print index(a,b)}‘
3.
echo $a | grep -bo cat | sed ‘s/:.*$//‘
4.

You can use grep to get the byte-offset of the matching part of a string:

echo $str | grep -b -o str

As per your example:

[[email protected] ~]$ echo "The cat sat on the mat" | grep -b -o cat4:cat

You can pipe this to awk if you just want the first part

echo $str | grep -b -o str | awk ‘BEGIN {FS=":"}{print $1}‘
echo $str | grep -b -o "cat" | cut -d: -f1

5 down vote

I used awk for this

a="The cat sat on the mat"test="cat"awk -v a="$a" -v b="$test" ‘BEGIN{print index(a,b)}‘

Position character position in shell string to get character position

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.