Array and string handling for bash script programming

Source: Internet
Author: User
Tags array definition

An array is a data structure that can be used to design algorithms more efficiently and easily for bash programming, which is described in detail in this chapter in the sections on arrays and strings.

Array array definition

An array is a contiguous memory space that stores multiple similar elements, and a variable is a memory space that stores a single element, compared to a variable.

Declaration array

Declare-a Array_Name
Declare-a array_name: Associative array

The assignment of an array element (1) assigns only one element at a time:

Array_name[index]=value

Example:

weekdays[0]= "Sunday"
Weekdays[4]= "Thursday"

(2) Assign all elements at once:

Array_name= ("VAL1" "VAL2" "VAL3" ...)

(3) Assign only specific elements:

Array_name= ([0]= "VAL1" [3]= "VAL2" ...)

(4) Read-a ARRAY

Associative array Assignment: array_name= ([index_name]= ' val1 ' [index_name2]= ' val2 ' ...)

Referencing array elements

${array_name[index]}

Index: Numbering starting from 0, which is a numeric index; note: Omitting [INDEX] means referencing an element with subscript 0
Note: An index can also use a custom format, not just a numeric format. BASH4.0 is supported, other languages called key value type
The array of bash supports sparse format;

Reference all elements: ${array[@]} ${array[*]}

The length of the array

(Number of elements in the array): ${#ARRAY_NAME [*]}, ${#ARRAY_NAME [@]}

Example 1:
Generate 10 random numbers and find their maximum and minimum values:
Declare-a Rand
Declare-i max=0

For i in {0..9}; Do
rand[$i]= $RANDOM
echo "${rand[$i]}"
[${rand[$i]}-gt $max] && max=${rand[$i]}
Done
echo "Max: $max"

Example 2:
Defines an array in which the elements in the array are all files ending in. Log in the/var/log directory, and the sum of the number of rows in the file that is labeled as even

declare-a files
Files= (/var/log/*.log)
Declare-i lines=0
For I in $ (seq 0 $[${#files [*]}-1]); Do
If [$[$i%2]-eq 0]; Then
Let lines+=$ (Wc-l ${files[$i]} | cut-d "-F1)
#= let lines+= ' Wc-l ${files[$i]} | Cut-d '-f1 '

Fi
Done
echo "Lines: $lines"

Array slices

${array[@]:offset:number} slices

Offset: Number of elements to skip
Number: The amount of elements to be fetched, all elements after the offset: ${array[@]:offset}

Append an element to an array

array[${#ARRAY [*]}]=

To delete an element in an array

Unset Array[index]


Bash string Processing tool string Slice

${var:offset:number}
Take the rightmost few characters of the string: ${var:-length}
Note : You must have a blank character after a colon

To take a substring based on a pattern

${var#*word}: Where word can be any of the specified characters: function: From left to right, find the var variable stored in the string, the first occurrence of Word, delete all characters from the beginning of the string to the first occurrence of Word characters
${var##*word}: Ditto, however, removes all characters from the beginning of the string to the last character specified by word (basename)
File= "/var/log/messages"
${file##*}: Messages
${var%word*}: Where Word is the specified character: function: From right to left, find the var variable stored in the string, the first occurrence of word, delete the last character of the string to the left to the first occurrence of all characters between word characters
File= "/var/log/messages"
Echo ${file%/*}
${var%%word*}: Ditto, except delete all characters from the rightmost character of the string to the left to the last occurrence of Word characters

Example: url=http://www.magedu.com:80
${url##:}: 80
${url%%:*}: http

Find replacements

${var/pattern/substi}: Finds the string that is represented by Var, the first time it is matched to by pattern, and replaces it with Substi
${var//pattern/substi}: Find the string shown in Var, all strings that can be matched to the pattern, and replace it with Substi
user=$ (head-1/etc/passwd)
Echo ${user/root/root}
${var/#pattern/substi}: Finds the string shown in Var, the string to which the beginning of the line is matched by pattern, to substi replace
${var/%pattern/substi}: Find the string shown in Var, the string to which the end of the line is matched by pattern, and replace it with Substi

Find Delete:

${var/pattern}: Delete String that was first matched by pattern
${var//pattern}: Delete the string that is so pattern matched
${var/#pattern}: Delete string with pattern match at beginning of line
${var/%pattern}: Delete string with pattern match at end of line

Character-Case conversions

${var^^}: Converts all lowercase characters in Var to uppercase
${var,}: Converts all uppercase characters in Var to lowercase

Assigning values to variables

${var:-value}: Returns value if Var is empty or not set, otherwise returns VAR
${var:=value}: If Var is empty or not set, return value and assign value to Var; otherwise, return the value of Var
${var:+value}: Returns the value of value if Var is not empty;
${var:?error_info}: Returns Error_info if Var is empty or not set, otherwise returns the value of Var

Using a configuration file for a script program

(1) Define a text file, each line defines "Name=value"
(2) Source This file in the script to

Array and string handling for bash script programming

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.