Linux Bash Shell Learning (8): shell programming basics-string operations

Source: Internet
Author: User

This article is also the second of the book note in Chapter 4 Basic shell programming of learning the bash shell 3rd edition, but we will not limit it to this.

String operation

In the following description, ":" Can be deleted. "Yes" means "exist but cannot be null". ":" means "exist ", this parameter can be left blank:

$ {

Varname

:-

Word

}

: If varname exists and is not null, the value of varname is returned; otherwise, word is returned. Returns a default value when a variable does not exist or is not defined. If$ {

Varname

-

Word

}

If varname exists, it can be null. For example, if myparam = is defined, the value of varname is returned. Otherwise, word is returned. You can also delete ":", which has the same meaning and does not repeat it.

$ {

Varname

: =

Word

}

: If varname exists and is not null, return the value of varname. Otherwise, assign a value to word and return the value. Set the default value for a non-existent or non-defined variable. The location parameter is read-only and cannot be assigned a value.

$ {

Varname

Message

}

: If varname exists and is not null, the value of varname is returned. Otherwise, the varname: Message is printed and the abort script is executed. If no message is set, the default "parameter null or not set" is used ". Used to check for errors that are not defined by variables.

$ {

Varname

: +

Word

}

: If varname exists and is not null, the value of word is returned. Otherwise, null is returned. Used to check whether a variable exists.

$ {

Varname

:

Offset

:

Length

}

: Obtain the substring operation. It returns a string of length starting from the offset position in varname. The first position is 0. If length is not given or is invalid (less than 0), all characters After offset are returned. If it is {@: offset: length }, returns the total length of the script parameter starting from the offset parameter.

The following is an example to learn their usage. We create a file and store some entries in it. We want to sort the entries, from large to small, and output the first n entries. The file is as follows:

[Wei @ wei-desktop bash-learning] $ cat myinfo

5 Depeche Mode

2 Split Enz

3 Simple Minds

1 Vivaldi, Antonio

20 Hello, world

7 adsf, dafdsf

15 Hello, myfriend

We created our script file highest for testing. The content is as follows: Other color fonts indicate instructions, not as part of the file. We use annotations without affecting File Execution.

# "#" Start indicates the comment line. A good habit is that the file information is provided at the beginning of the file for reading.

# Highest [howest]

# Sort the entry inf on a descend order, and high line the top

# [Hwomany] entry, default is 5

#
# Ask the user to give the parameter <File Name>. Otherwise, exit the script and ask the user to give the displayed entry. Otherwise, use the default value 5.

Filename =$ {1? 'Used command./test [entry_num] '}

Howtasks =$ {2:-5}

# The header is used to indicate certain information displayed during the output. If this line is commented out, it will not be displayed.

Header = set
# Echo has two parameters-n, indicating that LINEFEED is not executed after display, that is, line feed is not executed. -E Indicates parsing/n, which is considered as a line break without being two characters. If we comment out the header, nothing will be displayed.

Echo-e-n $ {header: + "num name/n "}

Echo-e-n $ {header: + "---- -----/n "}
# Sort is a sort command.-r indicates the reverse order, that is, from large to small.-n indicates that the first parameter is regarded as a number rather than a character. | Indicates pipe output, head-N

The first N rows are displayed.

Sort-nr $ filename | head-$ howtasks

Style matching

Pattern can contain wildcard. The operation is as follows:

  • $ {Variable

    #Pattern

    }

    : If the start of the variable matches pattern, the minimum match is removed and the subsequent characters are returned. If the variable does not match, the variable is given.

  • $ {Variable

    ##Pattern

    }

    : If the variable starts to match pattern, the maximum match is removed and the following characters are returned. If the variable does not match, the variable is given.

  • $ {Variable

    %Pattern

    }

    : If the last pattern of the variable matches, the minimum value is removed.

    Match: returns the previous character. If the character does not match, a variable is given.

  • $ {Variable

    %Pattern

    }

    : If the last match of the variable matches pattern, the maximum match is removed.

    If not, a variable is given.

  • $ {Variable

    /Pattern/string

    }

    : Replace the first match with a string. If the string is null, It is deleted. If variable is @ or *, the command is executed based on the command parameters.

  • $ {Variable

    //Pattern/string

    }

    : Replace all matches with string. If string is null, It is deleted. If variable is @ or *, the command is executed based on the command parameters.

The maximum or minimum criticism only differs when Wildcards are contained. No, exact matching is not the same. The following is an example.

[Wei @ wei-desktop bash-learning] $ echo $ aa

Abc. xyz. hello. world

[Wei @ wei-desktop bash-learning] $ echo $ {aa #*.}

Xyz. hello. world

[Wei @ wei-desktop bash-learning] $ echo $ {aa ##*.}

World

[Wei @ wei-desktop bash-learning] $ echo $ {aa % .*}

Abc. xyz. hello

[Wei @ wei-desktop bash-learning] $ echo $ {aa % .*}

Abc

[Wei @ wei-desktop bash-learning] $ echo $ {aa /./-}

Abc-xyz.hello.world

[Wei @ Wei-desktop bash-learning] $ echo $ {AA //./-}

ABC-XYZ-Hello-world

Pattern matching is often used for processing file names, such as removing the path name and obtaining the file suffix or prefix.

Check whether the extglob option is enabled: shopt | grep extglob. If it is enabled, you can use or extend the style match. Open shopt-s exglob, disable use-u. You can use these to replace wildcards:

  • *(Patternlist

    )

    The paternlist format is pattern1 | pattern2 | pattern3 | ...., Matches 0 or more pattern

  • + (Patternlist

    )

    Matches one or more pattern

  • ? (Patternlist

    )

    Matches 0 or 1 pattern.

  • @(Patternlist

    )

    Matches one pattern.

  • ! (Patternlist

    )

    Does not match any pattern.

For example, the value of echo $ {aa // + (abc | hello)/ALICE} is ALICE. xyz. ALICE. world.

Length operation

$ {#Varname

}

In the preceding example, $ {# aa} is 19.

Command substutuion: assign a value using the command input.

You can useCommand substitution

To set the parameter value. The command output can be assigned a value as a variable. In makefile writing, we used a similar method, namely 'pkg-config clutter-1.0 -- libs'. Here, ''contains the output result of command execution. However, this method is used to be compatible with the old version. You can use $ (UNIX command

. This method can be nested, And the UNIX command in it can also be command substitution. However, nesting cannot be implemented using ''. The following are some examples:

  • $ (Ls $ (PWD) to show the files in the current directory. For example, $ (ls $ home) provides the user directory ~ .
  • For example, type-all-path command provides the command path. If you need to carefully check the relevant file attributes, you can use LS-L $ (Type-all-path VI ).
  • VI $ (grep-l 'COMMAND substitution 'Ch *) indicates to edit the file containing 'COMMAND substitution' in the current directory, where-indicates, only the target file is displayed.


Cut and awk usage: Get column information

These two methods are applicable to obtaining columns. The old BSD system does not provide cut and needs to use awk instead. Use cut-fN-dC filename or awk-FC '{print $ N}' filename. N indicates the list, and C indicates the delimiter. The default value is tab. If we use space, it can be ''. If we use | or produce a special match, we use the/| method. For example, the user name cat/etc/passwd | cut-f1-d: is displayed :. For the output of the command in stdout, use spaces for it, for example, who. We can use the-cX-Y parameter, it indicates the starting character X to the Y character, and the X starts from 1. If Y is not displayed, it indicates that it is always until the end. For example, who | cut-c10-15

A small example of a stack

The following is an example of a FILO stack to review string operations.

Push_func ()

{

# Note: If the func parameter is not provided, it will jump out of func instead of ending the entire script.

Entry =$ {1 :? "Please enter the entry as push_func Param "}

# Note that there is a space behind the bottow. We use space as the separator. This is used for the last entry of pop.

Mystack = "$ entry $ {mystack:-bottow }"

Echo "Push $ entry in stack: $ mystack"

}

Pop_func ()

{

# Delete the top entry

Mystack =$ {mystack #*''}

# Obtain the top element of the current stack

.

Entry =$ {mystack % *}

Echo "After Pop, top entry is '$ entry', stack is $ mystack"

}

Push_func one

Push_func

Push_func two

Pop

Pop

Pop

Related links:
My articles on Linux operations

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.