Shell Script string interception

Source: Internet
Author: User
Tags first string rfc

Problems with the interception of shell strings:

The Linux shell intercepts the first 8 bits of a character variable, with the following methods:

1.expr substr "$a" 1 8

2.echo $a |awk ' {print substr (, 1,8)} '

3.echo $a |cut-c1-8

4.expr $a: ' \ (. \ \). * '

5.echo $a |dd Bs=1 count=8 2>/dev/null

Second, intercept by the specified string

1. The first method: ${varible##*string} The string after the last string from left to right ${varible#*string} intercepts the string after the first string from left to right ${varible%%string*} The string after the last string is intercepted from right to left ${varible%string*} The string "*" after the first string from right to left is just a wildcard character.

Example: $ myvar=foodforthought.jpg $ echo ${MYVAR##*FO} rthought.jpg $ echo ${myvar#*fo} odforthought.jpg

2, the second method: ${varible:n1:n2}: Intercept the variable varible the string from N1 to N2.

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.

Third, according to the specified requirements division: For example, get suffix name ls-al | Cut-d "."-f2

First, construct a string
Direct construction of Str_zero=hello str_first= "I am a string" str_second= ' success '
Repeat #repeat the first parm ($) by $ strrepeat () {local x=$2 if ["$x" = = ""]; Then x=0 fi
Local str_temp= "" While [$x-ge 1]; Do str_temp= ' printf "%s%s" "$STR _temp" "$" ' x= ' expr $x-1 ' Done echo $STR _temp}
Example: str_repeat= ' strrepeat ' $USER _name "3 ' echo" REPEAT = $STR _repeat "
Second, assignment and copy
Direct assignment is the same as constructing a string User_name=terry
Assigning values from variables aliase_name= $USER _name
Third, join
Directly joins two strings str_temp= ' printf '%s%s "" $STR _zero "" $USER _name "' use printf for more complex joins
Iv. seeking for length
Number of characters (char) count_char= ' echo ' $STR _first ' | Wc-m ' echo $COUNT _char
Number of bytes (byte) count_byte= ' echo ' $STR _first ' | Wc-c ' echo $COUNT _byte
Word count_word= ' echo ' $STR _first | Wc-w ' echo $COUNT _word
V. Comparison
Equality Comparison str1 = str2
Unequal comparison str1! = str2
Example: If ["$USER _name" = "Terry"]; Then echo "I am Terry" fi
Less than comparison #return 0 if the and the string is equal, return 1 if $ < $, Else 2strCompare () {local x=0 if [""! = "$"]; n x=2 localtemp= ' printf "%s\n%s" "$" "$" ' Local temp2= ' (echo "$"; echo "$") |sort ' if ["$TEMP" = "$TEMP 2"]; Then X=1 fi fi Echo $x}
VI. Testing
Sentence null-Z str
Award non-null-n-STR
is the number # return 0 if the string is num, otherwise 1 strisnum () {local ret=1 if [-N '], then local str_temp= ' echo ' $ ' | Sed ' s/[0-9]//g ' if [-Z ' $STR _temp "]; Then ret=0 fi fi Echo $RET}
Example: if [-N "$USER _name"]; Then echo "My name was not empty" fi
Echo ' Strisnum ' 9980 "'
Seven, Division
With the symbol + as the quasi, divides the character into the left and right two parts uses the SED example: the command date--rfc-3339 seconds output is 2007-04-14 15:09:47+08:00 takes its + left part date--rfc-3339 seconds | Sed ' s/+[0-9][0-9]:[0-9][0-9]//g ' output for 2007-04-14 15:09:47 take + right part date--rfc-3339 seconds | Sed ' s/.*+//g ' output is 08:00
A string split with a space separator using awk example: str_fruit= "Banana 0.89 100" Take the 3rd field echo $STR _fruit | awk ' {print $;} '
Eight, substring
String 1 is a substring of String 2 # return 0 is substring of $, otherwise 1 strissubstring () {Local x=1 case "$" in *$1*) x=0;; Esac Echo $x}

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

An expression meaning
${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.

[[email protected] ~]$ echo ${abc-' OK '} OK [[email protected] ~]$ echo $ABC

[[email protected] ~]$ echo ${abc= ' OK '} OK [[email protected] ~]$ echo $abc OK

If ABC does not declare "=" It will also assign a value to ABC.

[Email protected] ~]$ var1=11;var2=12;var3= [[email protected] ~]$ echo ${[email protected]} var1 var2 VAR3 [[ Email protected] ~]$ 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.

Second, string operation (length, read, replace)

An expression meaning
${#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.

1. Length

[Email protected] ~]$ test= ' I love China ' [[email protected] ~]$ echo ${#test} 12

${#变量名} to get the string length

2. Intercept strings

[Email protected] ~]$ test= ' I love China ' [[E-mail protected] ~]$ echo ${test:5} e China [[email protected] ~]$ echo $ {TEST:5:10} e China

${variable Name: start: length} get substring

3. String deletion

[Email protected] ~]$ test= ' C:/windows/boot.ini ' [[email protected] ~]$ echo ${test#/} c:/windows/boot.ini [[Email Prote CTED] ~]$ Echo ${test#*/} windows/boot.ini [[email protected] ~]$ echo ${test##*/} boot. ini

[Email protected] ~]$ echo ${test%/*} c:/windows [[email protected] ~]$ 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.

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

4. String substitution

[Email protected] ~]$ test= ' C:/windows/boot.ini ' [[email protected] ~]$ echo ${test/\//\\} c:\windows/boot.ini [[email P Rotected] ~]$ 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.

Third, performance comparison

In the shell, through awk,sed,expr and so on can be implemented, the string above operation. Below we perform a performance comparison.

[Email protected] ~]$ test= ' C:/windows/boot.ini '
[[Email protected] ~]$ time for I in $ (seq 10000);d o a=${#test};d one;

Real 0m0.173s user 0m0.139s sys 0m0.004s

[[Email protected] ~]$ time for I in $ (seq 10000);d o a=$ (length of expr $test);d one;

Real 0m9.734s User 0m1.628s

The speed difference is hundreds of times, call external command processing, and built-in operator performance is very different. In shell programming, try to complete with built-in operators or functions. Similar results can occur with awk,sed.

Shell Script string interception

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.