Egrep and extended regular expressions, conditional expressions, and arithmetic operations

Source: Internet
Author: User
Tags shebang egrep

Egrep and extended regular expressions, conditional expressions, and arithmetic operations
Linux05

Linux05_01? Use and extend regular expressions in egrep
REGEXP: REGular EXPression. It may not represent its own meaning, but it is used for special meanings such as anchoring.
Pattern: filtering conditions used to filter text by combining metacharacters and characters of Regular Expressions

Regular Expression:
Basic REGEXP: Basic
Extended REGEXP: Extended

Basic regular expression:
.:
[]:
[^]:

Matching times:
*:
\? : 0 or 1 time
\ {M, n \}: At least m times, at most n times;

.*:

Anchored:
^:
$:
\ <, \ B:
\>, \ B:

\(\)
\ 1, \ 2, \ 3 ,...

Grep: a command that uses the mode defined by the basic regular expression to filter text;
-I: case insensitive
-V: no matching information is displayed.
-O: only the strings matching the pattern are displayed.
-- Color: The color of the matched string.
-E: use an extended regular expression.
----------------------------------------
-A n: used to display the after n rows of matched rows
-B n: used to display before n rows of matched rows
-C n: used to display the context n rows of matched rows
[Root @ localhost ~] # Grep -- color-C 1 '^ cpu'/proc/cpuinfo
Vendor_id: GenuineIntel
Cpu family: 6
Model: 42
--
Stepping: 7
Cpu MHz: 2394.571
Cache size: 3072 KB
--
Fpu_exception: yes
Cpuid level: 13
Wp: yes
---------------------------------------------
Extended regular expression:

Character match: same as regular expression
.
[]
[^]

Matching times:
*:
? : Not required \
+: Match the first character at least once
{M, n}: Not required \

Location anchoring: same as regular expressions
^
$
\ <
\>

GROUP:
(): Group in the true sense, do not need \
\ 1, \ 2, \ 3 ,...

Or
|: Or
C | cat: C or cat
(C | c) at: Cat or cat
Grep-E = egrep

255:
One digit: 9 [0-9]
Two digits: 99 [1-9] [0-9]
Three Places: 199 1 [0-9] [0-9]; 249 2 [0-4] [0-9]; 255 2 [0-5] [0-5]
You can exit through the above: \ <([0-9] | [1-9] [0-9] | 1 [0-9] [0-9] | 2 [0-4] [0 -9] | 25 [0-5]) \>

4. All files ending with numbers and whose names do not contain spaces are displayed;
Ls * [^ [: space:] * [0-9] ???


Find the number between 1-In the/boot/grub. conf file;
\ <([1-9] | [1-9] [0-9] | 1 [0-9] [0-9] | 2 [0-4] [0 -9] | 25 [0-5]) \>

\.

Ifconfig | egrep '\ <([0-9] | [1-9] [0-9] | 1 [0-9] [0-9] | 2 [0-9- 4] [0-9] | 25 [0-5]) \> \. \ <([0-9] | [1-9] [0-9] | 1 [0-9] [0-9] | 2 [0-4] [0 -9] | 25 [0-5]) \> \. \ <([0-9] | [1-9] [0-9] | 1 [0-9] [0-9] | 2 [0-4] [0 -9] | 25 [0-5]) \> \. \ <([0-9] | [1-9] [0-9] | 1 [0-9] [0-9] | 2 [0-4] [0 -9] | 25 [0-5]) \>'

Ifconfig | egrep -- color '(\ <([0-9] | [1-9] [0-9] | 1 [0-9] [0-9] | 2 [0-4] [0-9] | 25 [0-5]) \> \.) {3 }\< ([0-9] | [1-9] [0-9] | 1 [0-9] [0-9] | 2 [0-4] [0-9] | 25 [0-5]) \>'

IPv4:
Category 5: A B C D E
A: 1-127: 00000000: 0: 0: 0 ~ 01111111: 255: 255: 255 network segments
B: 128-191 10000000: 0: 0: 0 ~ 10111111: 255: 255: 255 2-segment Network
C: 192-223 11000000: 0: 0: 0 ~ 11000000: 255: 255: 255 three-section Network

\ <([1-9] | [1-9] [0-9] | 1 [0-9] {2} | 2 [01] [0-9] | 22 [0-3]) \> (\. \ <([0-9] | [1-9] [0-9] | 1 [0-9] [0-9] | 2 [0-4] [0 -9] | 25 [0-4]) \>) {2 }\. \ <([1-9] | [1-9] [0-9] | 1 [0-9] [0-9] | 2 [0-4] [0 -9] | 25 [0-4]) \>


Http://mageedu.blog.51cto.com/


Grep, egrep
Fgrep: regular expressions are not supported.


Linux05_02? BashOne of Script Programming variables, variable types, etc.
Grep, egrep
Fgrep: regular expressions are not supported.



Shell programming:

Compiler, Interpreter

Programming Languages: machine language, assembly language, and advanced language

Static language: compiled language
Strong type (variable)
Convert to executable format in advance
C, C ++, JAVA, C #



Dynamic Language: interpreted language, on the fly
Weak type
Execute while interpreting
PHP, SHELL, python, perl

Relationship: Generally, the interpreter of a Dynamic Language is written in a static language.

Process-oriented: Shell and C
Object-oriented: JAVA, Python, perl, C ++

Variable: memory space, name

Memory: The address storage unit.

Process:
1 + 100:
1 + 1000000
1

Variable type: Determine the data storage format and length in advance
Character
Value
Integer
Floating Point: 11.23, 1.123*10 ^ 1, 0.1123*10 ^ 2
2013/10/10, 64bit
99999: 24bit,
Boolean
Logical operation: Same as, or, not, exclusive or
1: True
0: false
And :&
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
1 & 1 = 1

Or :!

Non:
! True = false
! False = true

Shell: weak Programming Language

Strong: variables must be declared in advance or even initialized before use;
Weak: declarations are made when variables are used, or even types are not differentiated;

Variable VALUE assignment: VAR_NAME = VALUE



Bash variable type:
Environment Variable
Local variable)
Location variable: \ 1, \ 2 ..
Special Variables

Local variable:
Set VARNAME = VALUE: the scope is the entire bash process;
---------------------------------
[Root @ localhost ~] # NAME = lvyongwen (no write type because shell is weak)
[Root @ localhost ~] # Echo $ NAME (printable)
Lvyongwen
[Root @ localhost ~] # Bash (subshell starts another shell process in shell)
[Root @ localhost ~] # Echo $ NAME (not printed, because the local variable is used for the entire shell process and the sub-shell cannot be obtained)

[Root @ localhost ~] # Exit
Exit
[Root @ localhost ~] # Echo $ NAME
Lvyongwen
[Root @ localhost ~] #
Reference variable: $ {VARNAME} {} can be omitted if there is no ambiguity
[Root @ localhost ~] # NAME = lvyongwen
[Root @ localhost ~] # Echo "My name is $ {NAME }"
My name is lvyongwen
[Root @ localhost ~] # Echo "My name is $ NAME"
My name is lvyongwen
[Root @ localhost ~] # Echo "My name is $ NAMEq"
My name is
[Root @ localhost ~] # Echo "My name is $ {NAME} q"
My name is lvyongwenq
[Root @ localhost ~] # Echo 'My name is $ {NAME} Q'
My name is $ {NAME} q has not printed the name because ''is of a strong reference type and cannot be replaced with variables." "is of a weak type, so you can
[Root @ localhost ~] #
------------------------------------
Local variables:
Local VARNAME = VALUE: the scope is the current code segment;

Environment variable: the scope is the current shell process and its sub-processes;
Define variable 1:
Export VARNAME = VALUE
Define variable 2:
VARNAME = VALUE
Export VARNAME
"Export"

Location variable:
$1, $2 ,...
Special variables:
$? : Return Value of the execution status of the previous command;

Program execution may have two types of return values:
Program Execution result
Code returned from the program status (0-255)
0: Correct execution
1-255: execution error, 127, reserved by the system;
[Root @ localhost ~] # Ls
Anaconda-ks.cfg DOS install. log test vms
C exit install. log. syslog test_dir
Desktop grant Solaris Unix
[Root @ localhost ~] # Echo $?
0
[Root @ localhost ~] # Lll
Bash: lll: command not found
[Root @ localhost ~] # Echo $?
127
[Root @ localhost ~] # Ls/ss
Ls:/ss: No such file or directory
[Root @ localhost ~] # Echo $?
2
-------------------------------------
Output redirection:
>
>
2>
2>
&>

/Dev/null: software device, bit bucket (bucket), data black hole
[Root @ localhost ~] # Ls &>/dev/null --> the output result will be eaten.
[Root @ localhost ~] # Echo $?
0
------------------------------------------
Undo variable:
Unset VARNAME

Check the local and environment variables in shell.
Set

View the environment variables in the current shell:
Printenv
Env
Export

The variable is saved to the memory as a string.
[Root @ localhost ~] # A = 2
[Root @ localhost ~] # B = 3
[Root @ localhost ~] # C = $ A + $ B
[Root @ localhost ~] # Echo $ C
2 + 3 <--- the preceding points are described here.

Script: the source program implemented by the command flow control mechanism based on actual needs.
-------------------------
Linux Kernel only recognizes: ELF file type: Executable link file
[Root @ localhost ~] # File/bin/ls
/Bin/ls: ELF 64-bit LSB executable, AMD x86-64...
[Root @ localhost ~] # File./test
./Test: ASCII text
For plain text, the following shebang tells the Linux kernel boot interpreter to explain
Shebang: Magic number
#! /Bin/bash
# Comment row, not executed
----
[Root @ localhost ~] # Cat adduser. sh
#! /Bin/bash <-- indicates that the command can be executed only when Linux calls the Linux kernel interpreter.
Adduser user1
Echo "user1" | passwd -- stdin user1 &>/dev/null
Echo "Add user1 successfully ."
[Root @ localhost ~] # Bash adduser. sh <-- run as a parameter,
Add user1 successfully.
[Root @ localhost ~] # Tail-1/etc/passwd
User1: x: 5001: 5001:/home/user1:/bin/bash
[Root @ localhost ~] # Nano adduser. sh
[Root @ localhost ~] # Adduser. sh <-- because it is not configured in the PATH environment variable
Bash: adduser. sh: command not found
[Root @ localhost ~] #./Adduser. sh <-- no value can be assigned for execution.
Bash:./adduser. sh: Permission denied
[Root @ localhost ~] # Ls-l
Total 72
-Rw-r -- 1 root 107 Feb 1 adduser. sh // although Green, it is displayed because. sh is displayed by default.
[Root @ localhost ~] # Chmod + x adduser. sh
[Root @ localhost ~] #./Adduser. sh
Add user1 successfully.
[Root @ localhost ~] #
------------------------



The script starts a sub-shell process during execution;
Scripts started in the command line inherit the current shell environment variables;
Environment variables must be customized for scripts automatically executed by the system (not started by command lines;



Exercise: write a script to complete the following tasks:
1. Add five users, user1,..., user5
2. The password of each user is the same as the user name. The passwd command execution result is not displayed after the password is added;
3. After each user is added, it must be displayed that the user has been successfully added;
Useradd user1
Echo "user1" | passwd -- stdin user1 &>/dev/null
Echo "Add user1 successfully ."
Exercise: write a script to complete the following tasks:
1. Use a variable to save a user name;
2. Delete the users in this variable and delete their home directories;
3. displays information about the "user deleted successfully" class;
[Root @ localhost ~] # Clear
[Root @ localhost ~] # Cat userdel. sh
#! /Bin/bash
USERNAME = user02
Userdel-r $ USERNAME -->-r indicates that the directory email is deleted together.
Echo "delete user successfully! "

Linux05_03? BashConditional judgment in Script ProgrammingCondition determination:
If the user does not exist
Add a user to the password and display that the user is successfully added;
Otherwise
It is shown that if it is not already in, it is not added;

In bash, how does one implement conditional judgment?
Condition test type:
Integer Test
Character Test
File Test

Conditional test expression:
[Expression]
[[Expression]
Test expression

Integer comparison:
-Eq: test whether two integers are equal. For example, $ A-eq $ B.
-Ne: test whether two integers are unequal. They are not equal to true. They are equal to false;
-Gt: test whether a number is greater than the other. If the value is greater than, the value is true. Otherwise, the value is false;
-Lt: test whether one number is smaller than the other. If the value is smaller than, the value is true. Otherwise, the value is false;
-Ge: greater than or equal
-Le: less than or equal

The logical relationship between commands:
Logic and :&&
When the first condition is false, the second condition does not need to be judged and the final result already exists;
When the first condition is true, the second condition must be judged;
Logic or: |
When the first condition is true, the second condition does not need to be judged and the final result already exists;
When the first condition is false, the second condition must be judged;
Non-logical :! // Single object

If user user6 does not exist, add user user6
! Id user6 & useradd user6
Id user6 | useradd user6

If the number of lines in the/etc/inittab file exceeds 100, a large file is displayed;
['Wc-l/etc/inittab | cut-d'-f1'-gt 100] & echo "Large file ."

Variable name:
1. It can only contain letters, numbers, and underscores, and cannot start with a number;
2. It should not be the same as the existing environment variable in the system;
3. It is best to be well known;

If a user exists, the user is displayed; otherwise, the user is added;
Id user1 & echo "user1 exists." | useradd user1

If the user does not exist, add it. Otherwise, it is displayed as already exist;
! Id user1 & useradd user1 | echo "user1 exists ."

If the user does not exist, add and give the password; otherwise, it is displayed that the user already exists;
! Id user1 & useradd user1 & echo "user1" | passwd -- stdi × user1 | echo "user1 exists ."


Exercise and write a script to fulfill the following requirements:
1. Add three users: user1, user2, and user3. First, determine whether the user exists and does not exist before adding the user;
! Id user1 &>/dev/null & useradd user1 & echo "user1" | passwd -- stdin user1 &>/dev/null | echo "user1 exists"
2. After the user is added, it is displayed that a total of several users have been added; of course, they cannot include those not added because they existed in advance;
3. display the total number of users on the current system;
One type:
COUNT = 'wc-l/etc/passwd | cut-d'-f1'
Echo "$ COUNT users"
Two types:
Echo 'this system users counts is 'wc-l/etc/passwd | cut-d'-f1' ×
Echo "this system users counts is 'wc-l/etc/passwd | cut-d'-f1'" √

---------------------------------
[Root @ localhost ~] # Echo "$ NAMES" --> indicates that weak references can be replaced by reference variables.
Lvyongwen
[Root @ localhost ~] # Echo '$ names' --> note that strong references cannot be replaced by reference Variables
$ NAMES
[Root @ localhost ~] # Echo '"$ NAMES"' --> strongly referenced variables cannot be nested with weak referenced variables.
"$ NAMES"
[Root @ localhost ~] # Echo "'ls ./'"
Adduser. sh
......
[Root @ localhost ~] # Echo ''ls ./''
'Ls ./'
The preceding two results are described as follows:
Reverse references can be replaced by commands, and weak references can be nested with reverse reference commands, but strong references cannot.
[Root @ localhost ~] # Echo "ls./" --> indicates that weak references cannot be replaced by commands.
Ls ./
[Root @ localhost ~] # Echo '$ names'
-Bash: lvyongwen: command not found
Because reverse references refer to commands, the system reports that the commands are not found and that reverse references reference variables.
[Root @ localhost ~] # Echo 'id $ names'
Uid = 500 (lvyongwen) gid = 500 (lvyongwen) groups = 500 (lvyongwen)
[Root @ localhost ~] #
---------------------------------
Exercise and write a script to fulfill the following requirements:
Given a user:
1. If the UID is 0, the Administrator is displayed;
2. Otherwise, it is displayed as a common user;
One type:
NAME = "root"
['Grep "^ $ NAME"/etc/passwd | cut-d:-f3 '-eq 0] --> indicates that reverse references can be nested with weak reference Reference variables.
& Echo "this user is root"
| "This user is not root"
Two types:
NAME = user1
USERID = 'id-u $ name' --> indicates that variables can be referenced by Reverse references.
[$ USERID-eq 0] & echo "Adim" | echo "Commom user"

If the UID is 0
Show as Administrator
Otherwise
Displayed as a common user

NAME = user16
USERID = 'id-u $ name' --> command execution result
If [$ USERID-eq 0]; then
Echo "Admin"
Else
Echo "common user ."
Fi



NAME = user16
If ['id-u $ name'-eq 0]; then
Echo "Admin"
Else
Echo "common user ."
Fi


If id $ NAME; then --> Command Execution status result


Linux05_04? BashScript Programming 3 condition judgmentAnd its operations
Exercise: write a script
Determine whether there are users on the current system. The default shell is bash;
If yes, the number of such users is displayed; otherwise, the number of such users is displayed;
Grep "bash $"/etc/passwd &>/dev/null
RETVAL =$?
If [$ RETVAL-eq 0]; then

If grep "bash $"/etc/passwd &>/dev/null; then

Tip: to reference the execution result of a command, use command reference. For example, RESAULTS = 'wc-l/etc/passwd | cut-d:-f1 ';
The execution status result of a command must be directly executed and cannot be referenced. For example, the id command in the if id user1 sentence must not be enclosed by quotation marks;
If you want to assign the execution result of a command to a variable, use command reference, such as USERID = 'id-u user1 ';
If you want to save the execution status result of a command and use it as a condition for determining whether the command is successful or not, you need to execute the command first and then reference its status result, as shown in
Id-u user1
RETVAL =$?
This sentence cannot be written as RETVAL = 'id-u user1 ';


Exercise: write a script
Determine whether there are users on the current system. The default shell is bash;
If yes, the user name of one of them is displayed; otherwise, no such user is displayed;

Exercise: write a script
Specify a file, such as/etc/inittab.
Checks whether there are blank lines in this file;
If yes, the number of blank lines is displayed. Otherwise, no blank lines are displayed.
#! /Bin/bash
A = 'grep' ^ $ '/etc/inittab | wc-l'
If [$ A-gt 0]; then
Echo "$"
Else
Echo "meiyoukongw.hang"
Fi
-- By Zhang Shuai

#! /Bin/bash
FILE =/etc/inittab
If [! -E $ FILE]; then
Echo "No $ FILE ."
Exit 8
Fi

If grep "^ $" $ FILE &>/dev/null; then
Echo "Total blank lines: 'grep" ^ $ "$ FILE | wc-l '."
Else
Echo "No blank line ."
Fi

Exercise: write a script
Determine whether the UID and GID of a user are the same.
If the same, the user is displayed as "good guy"; otherwise, the user is displayed as "bad guy ".
#! /Bin/bash
USERNAME = user1
USERID = 'id-u $ username'
GROUPID = 'id-g $ username'
If [$ USERID-eq $ GROUPID]; then
Echo "Good guy ."
Else
Echo "Bad guy ."
Fi

Further requirement: Do not use the id command to obtain its id number;

#! /Bin/bash
#
USERNAME = user1
If! Grep "^ $ USERNAME \>"/etc/passwd &>/dev/null; then
Echo "No such user: $ USERNAME ."
Exit 1
Fi

USERID = 'grep "^ $ USERNAME \>"/etc/passwd | cut-d:-f3'
GROUPID = 'grep "^ $ USERNAME \>"/etc/passwd | cut-d:-f4'
If [$ USERID-eq $ GROUPID]; then
Echo "Good guy ."
Else
Echo "Bad guy ."
Fi






Exercise: write a script
A user is given and the password warning period is obtained;
Then, determine whether the user's password's validity period is earlier than the warning period;
Tip: calculation method. The maximum validity period minus the number of days in use is the remaining validity period;

If the value is smaller than, "Warning" is displayed; otherwise, "OK" is displayed ".

Round: discard all content after decimal point

#! /Bin/bash
W = 'grep "student"/etc/shadow | cut-d:-f6'
S = 'date + % s'
T = 'expr $ S/8080'
L = 'grep "^ student"/etc/shadow | cut-d:-f5'
N = 'grep "^ student"/etc/shadow | cut-d:-f3'
SY = $ [$ L-$ [$ T-$ N]

If [$ SY-lt $ W]; then
Echo 'warning'
Else
Echo 'OK'
Fi

-- By Dong Lidong


Exercise: write a script
Determines whether the total number of historical commands in the command history is greater than 1000. If the value is greater than, "Some command will gone." is displayed; otherwise, "OK" is displayed ".

The value assignment in the variable is saved as a string by default.
How to perform arithmetic operations in shell:
A = 3
B = 6
1. let arithmetic expression
Let C = $ A + $ B
2. $ [arithmetic expression]
C = $ [$ A + $ B]
3. $ (arithmetic expression ))
C =$ ($ A + $ B ))
4. expr arithmetic expression. There must be spaces between the operands and operators in the expression, and commands must be used for reference.
C = 'expr $ A + $ B'

-----------------------------------
Root: $1 $ DxJ53wWP $ 3ZpbWEjFJMgqzMMFgECOQ.: 16425: 0: 99999: 7 :::
The following is an explanation of each entry in the shadow file:
Login name
Login Name
Encrypted password
Encrypted password
Days since Jan 1, 1970 that password was last changed
The last time the password was modified is the number of days since January 1, January 1970, and the last time the password was modified.
Days before password may be changed
The shortest time is required to change the password.
Days after which password must be changed
The maximum validity period of the password that must be modified after the password is used
Days before password is to expire that user is warned
To remind the user of the number of days before the expiration of the set time, the password Quick Expiration warning time
Days after password expires that account is disabled
The time before the account is locked after the password expires.
Days since Jan 1, 1970 that account is disabled
How long will the Account be locked and the account will be locked?
A reserved field
Reserved Field
------------------------------------







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.