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

Source: Internet
Author: User
Tags bbcode first string truncated

Linux shell string operation detailed (length, read, replace, intercept, connect, compare, delete, position) 1. Linux Shell intercepts the first 8 bits of a character variable


There are several ways to implement this:

    1. Expr substr "$a" 1 8
    2. echo $a |awk ' {print substr (, 1,8)} '
    3. Echo $a |cut-c1-8
    4. echo $
    5. Expr $a: ' \ (. \ \).
    6. echo $a |dd Bs=1 count=8 2>/dev/null

2. Intercept by the specified string


(1) The first method:

A string after the last string is truncated from left to right
${varible##*string}
A string after the first string is truncated from left to right
${varible#*string}
A string after the last string is intercepted from right to left
${varible%%string*}
A string after the first string is intercepted from right to left
${varible%string*}
"*" is just a wildcard can not

Take a look at the following example:

$ myvar=foodforthought.jpg$ echo ${myvar##*fo}rthought.jpg$ Echo ${myvar#*fo}odforthought.jpg


(2) The second method:

${VARIBLE:N1:N2}: Intercepts the variable varible the N2 character starting from N1, forming a substring. You can select specific substrings by using a different form of variable extension, depending on the specific character offset and length. Try entering the following line in bash:

$ exclaim=cowabunga$ echo ${exclaim:0:3}cow$ Echo ${exclaim:3:7}abunga


This form of string truncation is simple, with only a colon separated to specify the starting character and substring length.

3. Split according to the specified requirements:


For example, get the suffix name

Ls-al | Cut-d "."-f2

Summary: Shell corresponding string processing method, according to the needs of flexible choice.

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:

Java code
    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} //Results
    3. Expr length $string //Result
    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   from $string to the left, remove the shortest matching substring     
    2. echo ${string#c*3}      //abc12342341   so nothing matches to     
    3. echo ${string#*c1*3}   //42341   from $ String to the left to remove the shortest matching substring     
    4. echo ${string# #a *3}    < span class= "comment" >//41      from the left of $string, removing the longest matching substring     
    5. echo ${string%3*1}     //abc12342   from $ Start the string to the right, removing the shortest matched substring     
    6. echo ${string%%3*1}    < span class= "comment" >//abc12      from $string to the right, 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 deletionJava 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.   
    9. $ echo ${test%/*}&NBSP;
    10. C:/WINDOWS&NBSP;
    11. $&NBSP;ECHO&NBSP;${TEST%%/*}&NBSP;
    12. &NBSP;
    13. #${variable name #substring regular expression} comes with substring from the beginning of the string and deletes the expression on the match.  
    14. #${variable name%substring regular expression} comes with substring from the end of the string and deletes the expression on the match.  
    15. #注意:${test##*/},${test%/*}  are the simplest way to get the file name, or the 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.