Linux shell string manipulation

Source: Internet
Author: User

Ext.: http://justcoding.iteye.com/blog/1963463

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 with the same value 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 $default is used 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 $default is used as its value *

${var+other}
If Var is declared, then its value is $other, otherwise it is 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, print $err_msg *

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

${!varprefix*}
Matches all previously declared variables beginning with Varprefix

${[email protected]}
Matches all previously declared variables beginning with 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, start extracting substrings from position $position

${string:position:length}
In $string, a substring of length $length is extracted starting from position $position

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

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

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

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

${string/substring/replacement}
Use $replacement to replace the first matching $substring

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

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

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

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

Instance:

read:

    1. $ echo ${abc-' OK '}
    2. Ok
    3. $ echo $ABC
    4. $ echo ${abc= ' OK '}
    5. Ok
    6. $ echo $ABC
    7. Ok
    8. #如果abc not declaring "=" also assigns a value to ABC.
    9. $ var1=11;var2=12;var3=
    10. $ echo ${[email protected]}
    11. Var1 var2 Var3
    12. $ echo ${!v*}
    13. Var1 var2 Var3
    14. #${!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

    1. string=abc12342341//equal sign two sides don't have spaces
    2. echo ${#string}//Result 11
    3. Expr length $string//Result 11
    4. 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

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

C code

    1. Str= "ABC"
    2. Expr index $str "a" # 1
    3. Expr index $str "B" # 2
    4. Expr index $str "x" # 0
    5. 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

    1. 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

    1. Echo ${string:4}//2342341 intercepts all subsequent strings starting from the 4th bit
    2. Echo ${string:3:3}//123 intercept back 3 bits from 3rd bit
    3. Echo ${string:3:6}//123423 intercept back 6 bits from 3rd bit
    4. echo ${string:-4}//2341: The right side has a space to intercept after 4 bits
    5. echo ${string: (-4)}//2341 ibid.
    6. Expr substr $string 3 3//123 intercept the last 3 bits starting from the 3rd bit

C code

    1. Str= "ABCdef"
    2. Expr substr "$str" 1 3 # 3 characters starting from the first position, ABC
    3. Expr substr "$str" 2 5 # takes 5 characters starting from the second position, Bcdef
    4. Expr substr "$str" 4 5 # 5 characters starting from the fourth position, Def
    5. Echo ${str:2} # Extracts a string starting from the second position, Bcdef
    6. Echo ${str:2:3} # Extracts 3 characters from the second position, BCD
    7. echo ${STR: (-6): 5} # Extracts a string to the left from the penultimate position, ABCDE
    8. 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

    1. 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
    2. Expr match $string ' \ ([a-c]*[0-9]*\) '//abc12342341
    3. Expr $string: ' \ ([a-c]*[0-9]\) '//ABC1
    4. 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

    1. Echo ${string#a*3}//42341 starts from the left of $string, removing the shortest matching substring
    2. Echo ${string#c*3}//abc12342341 so there's nothing to match
    3. Echo ${string#*c1*3}//42341 starts from the left of $string, removing the shortest matching substring
    4. echo ${string# #a *}//41 from the left of $string, removing the longest matching substring
    5. Echo ${string%3*1}//abc12342 starts from the right side of $string, removing the shortest matching substring
    6. Echo ${string%%3*1}//ABC12 starts from the right side of $string, removing the longest matching substring

C code

  1. Str= "ABBC,DEF,GHI,ABCJKL"
  2. 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)
  3. 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)
  4. echo ${str# "A*c"} # Output ABBC,DEF,GHI,ABCJKL because there is no "a*c" substring in str
  5. echo ${str## "A*c"} # Output ABBC,DEF,GHI,ABCJKL similarly
  6. Echo ${str#*a*c*} # Empty
  7. Echo ${str##*a*c*} # Empty
  8. echo ${str#d*f) # output ABBC,DEF,GHI,ABCJKL,
  9. echo ${str#*d*f} # OUTPUT, GHI,ABCJKL
  10. Echo ${str%a*l} # Abbc,def,ghi a percent semicolon (%) that captures the shortest match from the right
  11. Echo ${str%%b*l} # A two percent sign (%) indicates the longest match is intercepted from the right
  12. 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

    1. Echo ${string/23/bb}//abc1bb42341 Replace once
    2. Echo ${string//23/bb}//abc1bb4bb41 double slash replaces all matches
    3. echo ${string/#abc/bb}//bb12342341 #以什么开头来匹配, the ^ in root PHP is a bit like
    4. Echo ${string/%41/bb}//abc123423bb% with what end to match, Root PHP is a bit like

C code

    1. Str= "Apple, tree, apple tree"
    2. Echo ${str/apple/apple} # Replaces the first occurrence of the apple
    3. Echo ${str//apple/apple} # Replace All Apple
    4. echo ${str/#apple/apple} # If the string str starts with Apple, replace it with Apple
    5. Echo ${str/%apple/apple} # If the string str ends with Apple, replace it with Apple

C code

    1. $ Test= ' C:/windows/boot.ini '
    2. $ echo ${test/\//\\}
    3. C:\windows/boot.ini
    4. $ echo ${test//\//\\}
    5. C:\windows\boot.ini
    6. #${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

    1. [["a.txt" = = *]] # logic true (pattern matching)
    2. [["A.txt" =~. *\.txt]] # logic true (regex matching)
    3. [["abc" = = "abc"]] # logic True (string comparision)
    4. [[["One" < "2"]] # Logical True (string comparision), compared by ASCII value

9. Connect

C code

    1. s1= "Hello"
    2. S2= "World"
    3. 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

    1. $ Test= ' C:/windows/boot.ini '
    2. $ echo ${test#/}
    3. C:/windows/boot.ini
    4. $ echo ${test#*/}
    5. Windows/boot.ini
    6. $ echo ${test##*/}
    7. Boot. ini
    8. $ echo ${test%/*}
    9. C:/windows
    10. $ echo ${test%%/*}
    11. #${variable name #substring regular expression} starts with substring from the beginning of the string and deletes the expression on the match.
    12. #${variable name%substring regular expression} starts with substring from the end of the string and deletes the expression on the match.
    13. #注意: ${test##*/},${test%/*} is the simplest way to get the file name, or directory address, respectively.

Linux shell string manipulation

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.