Linux shell string operation details (length, read, replace, intercept, connect, compare, delete, position)

Source: Internet
Author: User


String-related operations are often involved in the shell batch process. There are a lot of command statements, such as: awk,sed can do string various operations. In fact, the shell built a series of operating symbols, you can achieve similar effects, you know, using internal operators will omit the start of external programs and other time, so the speed will be very fast.

First, Judge read the string value

Meaning of an expression

${var} variable var value, same as $var

${var-default} if Var is not declared, then use $default as its value *

${var:-default} if Var is not declared, or its value is empty, then use $default as its value *

${var=default} if Var is not declared, then use $default as its value *

${var:=default} if Var is not declared, or its value is empty, then use $default as its value *

${var+other} if Var is declared, then its value is $other, otherwise it will be a null string

${var:+other} if Var is set, then its value is $other, otherwise it will be a null string

${var? ERR_MSG} if Var is not declared, then print $err_msg *

${var:? ERR_MSG} if Var is not set, then print $err_msg *

${!varprefix*} matches all variables declared at the beginning of Varprefix

${[email protected]} matches all previous variables declared at the beginning of the Varprefix

Adding "*" does not mean: Of course, if the variable var is already set, then its value is $var.

Second, string operation (length, read, replace)

Meaning of an expression

${#string} length of $string

${string:position} in $string, extract the substring from position $position

${string:position:length} in $string, start extracting substrings of length $length from position $position

${string#substring} removes the substring of the shortest match $substring from the beginning of the variable $string

${string# #substring} Remove the substring of the longest matching $substring from the beginning of the variable $string

${string%substring} removes the substring of the shortest match $substring from the end of the variable $string

${string%%substring} Remove the substring of the longest matching $substring from the end of the variable $string

${string/substring/replacement} uses $replacement instead of the first matching $substring

${string//substring/replacement} uses $replacement instead of all matching $substring

${string/#substring/replacement} if the $string prefix matches $substring, then $replacement is used instead of the matching $substring

${string/%substring/replacement} if the $string suffix matches $substring, then $replacement is used instead of the matching $substring

Description: "* $substring" can be a regular expression.

Instance:

Read:

Java Code Collection Code

$ echo ${abc-' OK '}

Ok

$ echo $ABC

$ echo ${abc= ' OK '}

Ok

$ echo $ABC

Ok

#如果abc not declaring "=" also assigns a value to ABC.

$ var1=11;var2=12;var3=

$ echo ${[email protected]}

Var1 var2 Var3

$ echo ${!v*}

Var1 var2 Var3

#${!varprefix*} similar to ${[email protected]}, a variable name prefix character can be used to search for a variable that has already been defined, regardless of whether it is a null value.

1, get string length

C Code Collection Code

string=abc12342341//equal sign two sides don't have spaces

echo ${#string}//Result 11

Expr length $string//Result 11

Expr "$string": ". *"//Result 11 The semicolon has a space on the two sides, here: the usage of the root match is almost

2, where the string is located

C Code Collection Code

Expr index $string ' 123 '//result 4 the string corresponding to the subscript is starting from 1

C Code Collection Code

Str= "ABC"

Expr index $str "a" # 1

Expr index $str "B" # 2

Expr index $str "x" # 0

Expr index $str "" # 0

This method makes me think of JS IndexOf, a variety of languages on the way the operation of the string is the same direction, if there is a language basis, learning the shell will be very fast.

3, from the beginning of the string to the maximum length of the substring

C Code Collection Code

Expr match $string ' abc.*3 '//Result 9

The individual feels that this function is of little use and why it should start from the beginning.

4, String intercept

C Code Collection Code

Echo ${string:4}//2342341 intercepts all subsequent strings starting from the 4th bit

Echo ${string:3:3}//123 intercept back 3 bits from 3rd bit

Echo ${string:3:6}//123423 intercept back 6 bits from 3rd bit

echo ${string:-4}//2341: The right side has a space to intercept after 4 bits

echo ${string: (-4)}//2341 ibid.

Expr substr $string 3 3//123 intercept the last 3 bits starting from the 3rd bit

C Code Collection Code

Str= "ABCdef"

Expr substr "$str" 1 3 # 3 characters starting from the first position, ABC

Expr substr "$str" 2 5 # takes 5 characters starting from the second position, Bcdef

Expr substr "$str" 4 5 # 5 characters starting from the fourth position, Def

Echo ${str:2} # Extracts a string starting from the second position, Bcdef

Echo ${str:2:3} # Extracts 3 characters from the second position, BCD

echo ${STR: (-6): 5} # Extracts a string to the left from the penultimate position, ABCDE

echo ${STR: (-4): 3} # Extract 6 characters to the left from the penultimate position, CDE

The above approach reminds me of PHP's substr function, which is the same as the rules behind the interception.

5. Match Display content

C Code Collection Code

In Example 3 there is a match and match here, which shows the length of the matching character, and the following is the matching content

Expr match $string ' \ ([a-c]*[0-9]*\) '//abc12342341

Expr $string: ' \ ([a-c]*[0-9]\) '//ABC1

Expr $string: '. *\ ([0-9][0-9][0-9]\) '//341 shows what matches in parentheses

The use of parentheses here, is not the root of other parentheses usage have similarities?

6. Intercept mismatched content

C Code Collection Code

Echo ${string#a*3}//42341 starts from the left of $string, removing the shortest matching substring

Echo ${string#c*3}//abc12342341 so there's nothing to match

Echo ${string#*c1*3}//42341 starts from the left of $string, removing the shortest matching substring

echo ${string# #a *}//41 from the left of $string, removing the longest matching substring

Echo ${string%3*1}//abc12342 starts from the right side of $string, removing the shortest matching substring

Echo ${string%%3*1}//ABC12 starts from the right side of $string, removing the longest matching substring

C Code Collection Code

Str= "ABBC,DEF,GHI,ABCJKL"

echo ${str#a*c} # Output, def,ghi,abcjkl a pound sign (#) means that the shortest match is intercepted from the left (the ABBC string is removed here)

echo ${str# #a *c} # Output JKL, two pound sign (# #) means the longest match is intercepted from the left (the ABBC,DEF,GHI,ABC string is removed here)

echo ${str# "A*c"} # Output ABBC,DEF,GHI,ABCJKL because there is no "a*c" substring in str

echo ${str## "A*c"} # Output ABBC,DEF,GHI,ABCJKL similarly

Echo ${str#*a*c*} # Empty

Echo ${str##*a*c*} # Empty

echo ${str#d*f) # output ABBC,DEF,GHI,ABCJKL,

echo ${str#*d*f} # OUTPUT, GHI,ABCJKL

Echo ${str%a*l} # Abbc,def,ghi a percent semicolon (%) that captures the shortest match from the right

Echo ${str%%b*l} # A two percent sign (%) indicates the longest match is intercepted from the right

Echo ${str%a*c} # ABBC,DEF,GHI,ABCJKL

Note here that you must start with the first character of the string, or, from the last one, to remember that the pound sign (#) is usually used to denote a number, which is placed in the front, and the percent sign (%) behind the unloaded number; Or so, in the keyboard layout, the pound sign (#) is always on the left side of the percent (that is, the front).

7, Match and replace

C Code Collection Code

Echo ${string/23/bb}//abc1bb42341 Replace once

Echo ${string//23/bb}//abc1bb4bb41 double slash replaces all matches

echo ${string/#abc/bb}//bb12342341 #以什么开头来匹配, the ^ in root PHP is a bit like

Echo ${string/%41/bb}//abc123423bb% with what end to match, Root PHP is a bit like

C Code Collection Code

Str= "Apple, tree, apple tree"

Echo ${str/apple/apple} # Replaces the first occurrence of the apple

Echo ${str//apple/apple} # Replace All Apple

echo ${str/#apple/apple} # If the string str starts with Apple, replace it with Apple

Echo ${str/%apple/apple} # If the string str ends with Apple, replace it with Apple

C Code Collection Code

$ Test= ' C:/windows/boot.ini '

$ echo ${test/\//\\}

C:\windows/boot.ini

$ echo ${test//\//\\}

C:\windows\boot.ini

#${variable/find/Replace value} A "/" means replacing the first, "//" means replacing all, when the lookup appears: "/" Please add escape character "/" to indicate.

8. Compare

C Code Collection Code

[["a.txt" = = *]] # logic true (pattern matching)

[["A.txt" =~. *\.txt]] # logic true (regex matching)

[["abc" = = "abc"]] # logic True (string comparision)

[[["One" < "2"]] # Logical True (string comparision), compared by ASCII value

9. Connect

C Code Collection Code

s1= "Hello"

S2= "World"

Echo ${s1}${s2} # Of course it's OK to write $s 1$s2, but it's best to add braces

10. String deletion

Java Code Collection Code

$ Test= ' C:/windows/boot.ini '

$ echo ${test#/}

C:/windows/boot.ini

$ echo ${test#*/}

Windows/boot.ini

$ echo ${test##*/}

Boot. ini

$ echo ${test%/*}

C:/windows

$ echo ${test%%/*}

#${variable name #substring regular expression} starts with substring from the beginning of the string and deletes the expression on the match.

#${variable name%substring regular expression} starts with substring from the end of the string and deletes the expression on the match.

#注意: ${test##*/},${test%/*} is the simplest way to get the file name, or directory address, respectively.


Linux shell string operation details (length, read, replace, intercept, connect, compare, delete, 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.