Shell command Set

Source: Internet
Author: User
Tags arithmetic arithmetic operators bitwise bitwise operators clear screen echo command set background

Shell Common knowledge points
---------------------------------------

SED usage http://www.cnblogs.com/edwardlost/archive/2010/09/17/1829145.html
SED is a non-interactive editor. It does not modify the file unless you use Shell redirection to save the results. By default, all output lines are printed to the screen.
SED does not like grep, regardless of whether the specified pattern is found, its exit status is 0. The exit status of SED is not 0 only if there is a syntax error in the command.
The sed command tells SED how to handle each input line specified by the address, and all input lines are processed if no address is specified.

1. Simple replacement
Sed-i "s/123/456/" <file>//i insert text

eg
Echo 123 > Sed.txt
Sed-i "s/123/456/" Sed.txt
Cat Sed.txt
[Email protected]:~/myworkspace/sed$ cat Sed.txt
456

The-p address is a number that represents the line number; is the "$" symbol, which indicates the last line
------------------
e.g.
Sed-n ' 3p ' datefile//outputs the contents of the third line
Sed-n ' 100,200p ' datefile//view the contents of the 100~200 line
Sed '/my/p ' datefile//outputs match to my line and print all other content again, if no match output other content
Sed-n '/my/p ' datefile//Output only the contents of the matching rows

-D
--------------------
Sed ' 2,5d ' datafile #删除第二到第五行 output other content
Sed '/my/,/you/d ' datafile #删除包含 line of "My" to rows that contain "you"
Sed '/my/,10d ' datafile #删除包含 "My" to the contents of line tenth

-S
-----------------------
Sed ' s/^my/you/g ' datafile #命令末端的g表示在行内进行全局替换, that is, if a line appears multiple my, all my my is replaced with you.
Sed-n ' 1,20S/MY$/YOU/GP ' datafile #取消默认输出, process 1 to 20 lines matching the line ending with my, replace all my in line with you and print to the screen.
Sed ' s#my#your#g ' datafile #紧跟在s命令后的字符就是查找串和替换串之间的分隔符.
Separating defaults is considered a forward slash, but can be changed. No matter what character (except newline, backslash), as soon as the S command is followed, a new string delimiter is formed.

-E-E is an edit command that is used in cases where SED performs multiple editing tasks. All edit actions are applied to the line in the pattern buffer before the next line starts editing
--------------------
Sed-e ' 1,10d '-e ' s/my/your/g ' datafile #选项-E for multiple edits. The first edit deletes the 第1-3 line.
The second editor replaces all occurrences of my with your. Because these two edits are performed line by row (that is, both commands are executed on the current line of the pattern space),
So the order in which you edit the commands affects the results.

The r command is a read command. SED uses this command to add the contents of a text file to a specific location in the current file.
----------
Sed '/my/r introduce.txt ' datafile
#如果在文件datafile的某一行匹配到模式My, the contents of the file Introduce.txt are read after the line.
If there is more than one row of my rows, the contents of the Introduce.txt file are read after the lines of my are present.

W command
------------------
Sed-n '/my/w me.txt ' datafile


Y command
-----------
Sed ' 1,20y/my12/my^$/' datafile
#将1到20行内, convert all lowercase hrwang to uppercase, convert 1 to ^, convert 2 to $.
#正则表达式元字符对y命令不起作用. As with the S command delimiter, the slash can be replaced with other characters.


2. Get the contents of the row for

Sed-n ' 1,NP ' <file>

eg
echo 123456 > Sed.txt
Sed-n ' 1p ' > Sed.log

Cat Sed.log
123456

3. Print mode matches the contents of the row

Sed-n '/What to look for/' P <file>

eg
[Email protected]:~/myworkspace/sed$ sed-n '/ro.build.display.id/' P build.prop
Ro.build.display.id=fiber_chiphd-eng 4.2.2 JDQ39 20140425 Test-keys

Sed
------
Options feature
-e multiple edits, which are used when multiple SED commands are applied to an input line
-N cancels the default output
-f Specifies the file name of the SED script


4. Judgment statement

1>. test of file name
-e filename true if filename exists
-d filename If filename is a directory, true
-F filename True if filename is a regular file
-L filename True if filename is a symbolic link
-r filename If filename is readable, true
-W filename if filename is writable, true
-x filename If filename is executable, true
-S filename true if the length of the file is not 0
-H filename True if the file is a soft link
Filename1-nt filename2 If filename1 is newer than filename2, it is true.
Filename1-ot filename2 If filename1 is older than filename2, it is true.
2>. Digital test
-eq is equal to true.
-ne is not equal to true.
-GT is greater than true.
-ge is true if it is greater than or equal.
-lt is less than true.
-le is less than or equal to true.
As for! The number is to take non-

Num1-eq num2 equals [3-eq $mynum]
Num1-ne num2 Not equal to [3-ne $mynum]
Num1-lt num2 less than [3-lt $mynum]
Num1-le num2 less than or equal to [3-le $mynum]
NUM1-GT num2 greater than [3-GT $mynum]
Num1-ge num2 greater than or equal to [3-ge $mynum]

3>. String test
= Equals is true.
! = is not equal to true.
-Z String string length pseudo is true.

The-n string string is true if the length is not pseudo.
-Z String True if string length is zero [-Z ' $myvar ']
-N String if string length is nonzero, true [-n ' $myvar ']
string1 = string2 If string1 is the same as string2, then true ["$myvar" = "One of the three"] determines whether $ A and $b are equal
String1! = string2 If string1 is different from string2, then true ["$myvar"! = "one, three"]

If ["$ver"];then
True if the string exists
Fi

First, Judge read the string value
The Bash shell can make conditional substitutions of variables, replacing them only when certain conditions occur, and substituting the conditions in {}.
(1) ${value:-word}
When the variable is undefined or the value is empty, the return value is the contents of Word, otherwise the value of the variable is returned.
(2) ${value:=word}
Similar to the former, except that if the variable is undefined or the value is empty, the word value is returned to value at the same time
(3) ${value:?message}
If the variable is assigned a value, replace it normally. Otherwise, send message messages to the standard error output (if this substitution appears in the shell program, the program will terminate running)
(4) ${value:+word}
If the variable is assigned, its value is replaced with Word, otherwise no substitution is made
(5) ${value:offset}
${value:offset:length} extracts substrings from the variable, where offset and length can be arithmetic expressions.
(6) ${#value}
The number of characters in a variable
(7) ${value#pattern}
${value# #pattern}
Remove the part of value that matches the pattern in the condition that the beginning of value matches the pattern
#与 # #的区别在于一个是最短匹配模式, one is the longest matching pattern.
(8) ${value%pattern}
${value%%pattern}
In (7) similar, just from the tail of value in pattern matching,% and percent of the difference between # and # #一样
(9) ${value/pattern/string}
${value//pattern/string}
Replace the contents of the variable with the content of the pattern match with the contents of the string, the difference between//and the
Note: In the above condition variable substitution, except (2), the rest does not affect the value of the variable itself

Second, string operation (length, read, replace)
Meaning of an expression
${#string} Length of $string
${string:position} in $string, extract the substring from position $position
${string:position:length} in $string, start extracting substrings of length $length from position $position
${string#substring} removes the substring of the shortest match $substring from the beginning of the variable $string
${string# #substring} Remove the substring of the longest matching $substring from the beginning of the variable $string
${string%substring} removes the substring of the shortest match $substring from the end of the variable $string
${string%%substring} Remove the substring of the longest matching $substring from the end of the variable $string
${string/substring/replacement} uses $replacement instead of the first matching $substring
${string//substring/replacement} uses $replacement instead of all matching $substring
${string/#substring/replacement} if the $string prefix matches $substring, then $replacement is used instead of the matching $substring
${string/%substring/replacement} If the $string suffix matches $substring, then $replacement is used instead of the matching $substring


String length calculation echo ${#test}//# take string length

4>. Arithmetic operators
+-*/% indicates subtraction and take-rest operations
+ = = *=/= with C language meaning

5>. Bitwise operators
> >>= means move one operation left and right
& &= | |= indicates bitwise AND, bit, or operation
~ ! Represents a non-operational
^ ^= represents XOR or manipulation

6>. Relational operators
= = = = = Greater than, less than, greater than or equal, less than equals, equals, not equal to operation
&& | | Logical AND logical OR operational

5. Notes
1.# Opening
2.


6. Find Usage

Find. -name \*
Find./-name "XXX"
Find. -mtime-1-type F-print is used to find files that have been modified in the last 24 hours (-mtime-2 represents the last 48 hours)

Find. -size +1000c-print

If you want to hit a package with all the files you find, you can use the following script

#!/bin/sh
TAR-ZCVF lastmod.tar.gz ' Find. -mtime-1-type F-print '

7. grep

8. awk

Find. -name proj_help.sh | awk-f/' {print $ (NF-4) '/'} '

9. The "If" expression if the condition is true then perform the following parts:
If ....; Then
....
Elif ...; Then
....
Else
....
Fi


The case expression can be used to match a given string instead of a number.

Case ... in

...) Do something here

Esac

The. Select expression is an extended application of bash and is especially adept at interactive use. Users can choose from a different set of values.

Select Var in ... do
  
Break
Done
.... Now $var can be used ....
eg

#!/bin/sh
echo "What's your favourite OS?"
Select Var in "Linux", "Gnu Hurd" "Free BSD" and "other"; Do
Break
Done
echo "You have selected $var"

The following is the result of the script running:
What is your favourite OS?
1) Linux
2) Gnu Hurd
3) Free BSD
4) Other
#? 1
You have selected Linux

While you can also use the following loop expression in the shell:

While ...; Do
....
Done

While-loop will run until the expression test is true. Would run while the expression, the We test for is true.
The keyword "break" is used to jump out of a loop. The keyword "Continue" is used to skip to the next loop without executing the rest of the section.

The For-loop expression looks at a list of strings (strings separated by spaces) and assigns them to a variable:

for Var in ...; Do
....
Done
eg
#!/bin/sh
For Var in A B Cdo
Echo "Var is $var"
Done


Echo
-------------------------
Word background color range: 40-49
40: Black
41: Crimson
42: Green
43: Yellow
44: Blue
45: Purple
46: Dark Green
47: White
-----------------------
Word Color: 30-39
30: Black
31: Red
32: Green
33: Yellow
34: Blue
35: Purple
36: Dark Green
37: White
-----------------------
ANSI Control code

\33[0m Close All Properties
\33[01m Setting High brightness
\33[04m Underline
\33[05m Flashing
\33[07M Reverse Display
\33[08m blanking
\33[30m--\33[37m setting foreground color
\33[40m--\33[47m Set background color
\33[na the cursor to move n rows
\33[NB cursor down n rows
\33[NC cursor right shifts n rows
\33[nd cursor left n rows
\33[Y;XH Setting the cursor position
\33[2J Clear Screen
\33[k clears the contents from the cursor to the end of the line
\33[s Save Cursor position
\33[u Restore cursor Position
\33[?25l Hide Cursor
\33[?25h Display cursor
----------------------------
eg
Echo-e "\033[31m xxx \033[0m"
Echo-e "\e[1;32m xxx \e[0m"

eg
#!/bin/bash
a=10
Echo-e "Value of A is $a \ n"
Operation Result:
Value of A is 10

-E indicates that the escape character is replaced. If you do not use the-e option

If there are no parameters, run the result:
Value of A is ten \ n


Tr

echo "HELLO who's This" | Tr ' A-Z ' A-Z '//Case Conversion
Cat File.txt | Tr-d ' 0-9 '//Remove the numbers tr-d

. sort


Parameters for Bash
$ $ return value
The first parameter
$ A second parameter
[Email protected] is extended to "$" "$" "$" (most used)
$* is extended to "$1c$2c$3"
$ #表示参数个数

For example,
The script name is called test.sh Three: 1 2 3
After running test.sh 1 2 3
$* is "1 2 3" (enclosed in quotation marks)
[Email protected] is "1" "2" "3" (separately wrapped)
$ #为3 (number of parameters)


$* [email protected] "[email protected]" "$" "$" "$ $"
"$*" "$ $"

17.linux Shell Search Command

Find
Locate
Whereis
which
Type

. Cut

echo $PATH | Cut-d:-F 3,5//Remove lines 3rd and 5th
Last | Cut-d '-F 1
Last | Cut-c 9-15
Last | Cut-c 9-
Last | Cut-d ""-F 1 | Sort | Uniq
Last | Cut-d ""-F 1 | Sort | Uniq-c

Rename Shell
eg
#!/bin/bash

Count=1;
For item in chapter*
Do
new=c${item##*}
MV "$item" "$new" 2>/dev/null
If [$?-eq 0];then
echo "Renaming $img to $new"
Let count++
Fi
Done

Shell debugging
The simplest debug command, of course, is to use the echo command. You can use Echo to print any variable value in any place where you suspect it is wrong.
That's why most shell programmers spend 80% of their time debugging programs. The advantage of a shell program is that it doesn't need to be recompiled, and it doesn't take much time to insert an echo command.

The shell also has a real debug mode. If there is an error in the script "Strangescript", you can debug it this way:
Sh-x Strangescript
This executes the script and displays the values of all variables.
  
The shell also has a pattern that does not need to execute a script just to check the syntax. This can be used:
Sh-n Your_script
  
This will return all syntax errors.

Shell return value

Common commands
------------------------------------
WC for statistical character count
The tree command is the protagonist of printing files and directories in a graphically structured structure.

command of the whole Zhi
------------------------------------
Godir
Mm
Mmm
Croot
Cdeives
cout
Cgrep
Resgrep
Jgrep

Delete a file in bulk
Find. -name ' xxx '-exec rm-r {} +

Shell command Set

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.