当前位置:网站首页>Shell (II)
Shell (II)
2022-07-28 11:41:00 【JiaXingNashishua】
Catalog
3、 ... and : Getting started with regular expressions
3.2 Special characters are often used
5、 ... and : Comprehensive application case
One :read Read console input
1) Basic grammar
read ( Options ) ( Parameters )
① Options :
-p: Specify the prompt when reading the value ;
-t: Specifies the time to wait while reading the value ( second ) If -t Not adding means waiting ② Parameters
Variable : Specifies the variable name of the read value
2) Case practice
Tips 7 Seconds , Read the name entered by the console
[[email protected] shells]$ touch read.sh
[[email protected] shells]$ vim read.sh
#!/bin/bash
read -t 7 -p "Enter your name in 7 seconds :" NN
echo $NN
[[email protected] shells]$ ./read.sh
Enter your name in 7 seconds : atguigu
atguiguTwo : function
2.1 System function
2.1.1 basename
1) Basic grammar
basename [string / pathname] [suffix] ( Function description :basename The command will delete all the previous
Including the last (‘/’) character , Then display the string .
basename It can be understood as taking the file name in the path
Options :
suffix For the suffix , If suffix Designated ,basename Will pathname or string Medium suffix Get rid of .
2) Case practice
Intercept this /home/atguigu/banzhang.txt File name of the path .
[[email protected] shells]$ basename /home/atguigu/banzhang.txt
banzhang.txt
[[email protected] shells]$ basename /home/atguigu/banzhang.txt .txt
banzhang
8.1.2 dirname
1) Basic grammar
dirname File absolute path ( Function description : Remove filename from given filename with absolute path ( Non catalog part ), Then return to the rest of the path ( Part of the catalog ))dirname It can be understood as the absolute path name of the file path
2) Case practice
obtain banzhang.txt Path to file .
[[email protected] ~]$ dirname /home/atguigu/banzhang.txt
/home/atguigu 2.2 Custom function
1) Basic grammar
[ function ] funname[()]
{
Action;
[return int;]
}2) Experience and skill
(1) Must be before calling function place , Declare function first ,shell The script is run line by line . Not like other languages
Sample compilation first .
(2) Function return value , Only through $? System variable acquisition , Can display plus :return return , If not , take
Run the result with the last command , As return value .return Heel value n(0-255)
3) Case practice
Calculate the sum of the two input parameters .
[[email protected] shells]$ touch fun.sh
[[email protected] shells]$ vim fun.sh
#!/bin/bash
function sum()
{
s=0
s=$[$1+$2]
echo "$s"
}
read -p "Please input the number1: " n1;
read -p "Please input the number2: " n2;
sum $n1 $n2;
[atguigu[email protected] shells]$ chmod 777 fun.sh
[[email protected] shells]$ ./fun.sh
Please input the number1: 2
Please input the number2: 5
73、 ... and : Getting started with regular expressions
Regular expressions are described using a single string 、 Match a series of strings that conform to a certain syntax rule . In many articles
In this editor , Regular expressions are often used for retrieval 、 Replace the text that matches a pattern . stay Linux in ,grep,
sed,awk And other text processing tools support pattern matching through regular expressions .
3.1 Regular match
A string of regular expressions without special characters matches itself , for example :
[[email protected] shells]$ cat /etc/passwd | grep atguiguIt will match all that contain atguigu The line of .
3.2 Special characters are often used
1) Special characters :^
^ Match the beginning of a line , for example :
[[email protected] shells]$ cat /etc/passwd | grep ^aIt will match all of them with a Beginning line
2) Special characters :$
$ Match the end of a line , for example
[[email protected] shells]$ cat /etc/passwd | grep t$It will match all of them with t The line at the end
3) Special characters :.
. Match an arbitrary character , for example
[[email protected] shells]$ cat /etc/passwd | grep r..t Will match to include rabt,rbbt,rxdt,root And so on
4) Special characters :*
* Not used alone , He used it with the last character , Means to match the previous character 0 Times or times , for example
[[email protected] shells]$ cat /etc/passwd | grep ro*tWill match rt, rot, root, rooot, roooot Wait for all the lines
5) Character range ( brackets ):[ ]
[ ] Means to match a character in a range , for example
[6,8]------ matching 6 perhaps 8
[0-9]------ Match one 0-9 The number of
[0-9]*------ Matches any length of numeric string
[a-z]------ Match one a-z Characters between
[a-z]* ------ Matches an alphabetic string of any length
[a-c, e-f]- matching a-c perhaps e-f Any character between
[[email protected] shells]$ cat /etc/passwd | grep r[a,b,c]*t
Will match rt,rat, rbt, rabt, rbact,rabccbaaacbt Wait, all right
6) Special characters :\
\ To signify an escape , It will not be used alone . Because all special characters have their own matching patterns , When we want to match
When a particular character itself ( for example , I want to find out all the things that contain '$' The line of ), There will be difficulties . At this point we will
Use escape characters with special characters , To represent the special character itself , for example
[[email protected] shells]$ cat /etc/passwd | grep ‘a\$b’It will match all that contain a$b The line of . Note that you need to use single quotes to cause the expression to .
Four : Text processing tools
4.1 cut
cut The job of “ cut ”, Specifically, it is used to cut data in the file .cut Command from every part of the file
Cut bytes in one line 、 Characters and fields and put these bytes 、 Character and field output .
1) Basic usage
cut [ Option parameters ] filename
explain : The default separator is tab 2) Option parameter description

3) Case practice
(1) Data preparation
[[email protected] shells]$ touch cut.txt
[[email protected] shells]$ vim cut.txt
dong shen
guan zhen
wo wo
lai lai
le le
(2) cutting cut.txt First column
[[email protected] shells]$ cut -d " " -f 1 cut.txt
dong
guan
wo
lai
le
(3) cutting cut.txt second 、 The three column
[[email protected] shells]$ cut -d " " -f 2,3 cut.txt
shen
zhen
wo
lai
le
(4) stay cut.txt Cut out in file guan
[[email protected] shells]$ cat cut.txt |grep guan | cut -d " " -f 1
guan
(5) Selection system PATH A variable's value , The first 2 individual “:” All paths after start :
[[email protected] shells]$ echo $PATH
/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/atguigu/.local/bin:/
home/atguigu/bin
[[email protected] shells]$ echo $PATH | cut -d ":" -f 3-
/usr/local/sbin:/usr/sbin:/home/atguigu/.local/bin:/home/atguigu/bin
(6) cutting ifconfig Post print IP Address
[[email protected] shells]$ ifconfig ens33 | grep netmask | cut -d " " -f 10
192.168.111.1014.2 awk
A powerful text analysis tool , Read the document line by line , Slice each line with a space as the default separator , Cut open
Then analyze and deal with the part of .
1) Basic usage
awk [ Option parameters ] ‘/pattern1/{action1} /pattern2/{action2}...’ filename
pattern: Express awk What to look for in the data , It's a matching pattern
action: A series of commands executed when a match is found 2) Option parameter description

3) Case practice
(1) Data preparation
[[email protected] shells]$ sudo cp /etc/passwd ./
passwd What data means
user name : password ( Encrypted ): user id: Group id: notes : User home directory :shell Parser
(2) Search for passwd Document to root All lines at the beginning of the keyword , And output the 7 Column .
[[email protected] shells]$ awk -F : '/^root/{print $7}' passwd
/bin/bash
(3) Search for passwd Document to root All lines at the beginning of the keyword , And output the 1 Column and the first 7 Column ,
In the middle to “,” Division of no. .
[[email protected] shells]$ awk -F : '/^root/{print $1","$7}' passwd
root,/bin/bash
Be careful : Only match pattern Will be executed action.
(4) Display only /etc/passwd The first and seventh columns of , Comma separated , And add column names before all rows user,
shell Add on last line "dahaige,/bin/zuishuai".
[[email protected] shells]$ awk -F : 'BEGIN{print "user, shell"}
{print $1","$7}
END{print "dahaige,/bin/zuishuai"}' passwd
user, shell
root,/bin/bash
bin,/sbin/nologin ...
atguigu,/bin/bash
dahaige,/bin/zuishuai
Be careful :BEGIN Execute before all data read rows ;END Execute after all data execution .
(5) take passwd Users in files id Increase in numerical value 1 And the output
[[email protected] shells]$ awk -v i=1 -F : '{print $3+i}' passwd
1
2
3
44)awk Built in variables for

5) Case practice
(1) Statistics passwd file name , Line number of each line , Columns per row
[[email protected] shells]$ awk -F : '{print "filename:" FILENAME ",linenum:"
NR ",col:"NF}' passwd
filename:passwd,linenum:1,col:7
filename:passwd,linenum:2,col:7
filename:passwd,linenum:3,col:7
... (2) Inquire about ifconfig The line number of the empty line in the command output result
[[email protected] shells]$ ifconfig | awk '/^$/{print NR}'
9
18
26
(3) cutting IP
[[email protected] shells]$ ifconfig ens33 | awk '/netmask/ {print $2}'
192.168.6.1015、 ... and : Comprehensive application case
5.1 The archive
In practical production application , It is often necessary to archive and back up important data .
demand : Implement a script that archives and backs up the specified directory every day , Enter a directory name ( It doesn't end with /),
Archive and save all files in the directory on a daily basis , And attach the filing date to the file name , Put it in /root/archive Next .
The archive command is used here :tar
You can add -c Option means archive , add -z Option means to compress at the same time , The resulting file suffix is .tar.gz.
The script is implemented as follows :
#!/bin/bash
# First, judge whether the number of input parameters is 1
if [ $# -ne 1 ]
then
echo " Wrong number of parameters ! You should enter a parameter , As the archive directory name "
exit
fi
# Get the directory name from the parameter
if [ -d $1 ]
then
echo
else
echo
echo " directory does not exist !"
echo
exit
fi
DIR_NAME=$(basename $1)
DIR_PATH=$(cd $(dirname $1); pwd)
# Get current date
DATE=$(date +%y%m%d)
# Define the name of the generated archive file
FILE=archive_${DIR_NAME}_$DATE.tar.gz
DEST=/root/archive/$FILE
# Start archiving catalog files
echo " Start filing ..."
echo
tar -czf $DEST $DIR_PATH/$DIR_NAME
if [ $? -eq 0 ]
then
echo
echo " Archive success !"
echo " Archive file is :$DEST"
echo
else
echo " There is a problem with archiving !"
echo
fi
exit5.2 Send a message
We can use Linux Self contained mesg and write Tools , Send messages to other users .
demand : Implement a script to quickly send messages to a user , Enter the user name as the first parameter , Straight back
Follow the message to be sent . The script needs to detect whether the user logs in to the system 、 Whether to turn on the message function , And the current issue
Whether the sending message is empty .
The script is implemented as follows :
#!/bin/bash
login_user=$(who | grep -i -m 1 $1 | awk '{print $1}')
if [ -z $login_user ]
then
echo "$1 Not online !"
echo " Script exit .."
exit
fi
is_allowed=$(who -T | grep -i -m 1 $1 | awk '{print $2}')
if [ $is_allowed != "+" ]
then
echo "$1 No message function is enabled "
echo " Script exit .."
exit
fi
if [ -z $2 ]
then
echo " No message was sent "
echo " Script exit .."
exit
fi
whole_msg=$(echo $* | cut -d " " -f 2- )
user_terminal=$(who | grep -i -m 1 $1 | awk '{print $2}')
echo $whole_msg | write $login_user $user_terminal
if [ $? != 0 ]
then
echo " fail in send !"
else
echo " Send successfully !"
fi
exit边栏推荐
- 【C语言】的%*d、%.*s等详解:「建议收藏」
- Unity鼠标带动物体运动的三种方法
- Function of interface test
- I/O实操之对象流(序列化与反序列化)
- How to use JWT for authentication and authorization
- 重新刷新你对Redis集群的理解
- 本地化、低时延、绿色低碳:阿里云正式启用福州数据中心
- Encryption defect of icloud Keychain in Apple mobile phone
- Solutions to the disappearance of Jupiter, spyder, Anaconda prompt and navigator shortcut keys
- Iterative method for determinant (linear algebraic formula)
猜你喜欢

目标检测领域必看的6篇论文

mysql还有哪些自带的函数呢?别到处找了,看这个就够了。
![完整版H5社交聊天平台源码[完整数据库+完整文档教程]](/img/3f/03239c1b4d6906766348d545a4f234.png)
完整版H5社交聊天平台源码[完整数据库+完整文档教程]

Cvpr2020 best paper: unsupervised learning of symmetric deformable 3D objects

融云 IM & RTC 能力上新盘点

What is WordPress
![Two point, three point, 01 point plan [bullet III]](/img/4c/a047440b4752c74c249d5e98bd4b3d.png)
Two point, three point, 01 point plan [bullet III]

The fifth generation verification code of "cloud centered, insensitive and extremely fast" is coming heavily

outlook突然变得很慢很卡怎么解决

Random talk on GIS data (V) - geographic coordinate system
随机推荐
Tiktok programmer confession special code tutorial (how to play Tiktok)
ZBrush 2022软件安装包下载及安装教程
使用c语言实现双向链表
ASP. Net core 6 framework unveiling example demonstration [29]: building a file server
Router firmware decryption idea
「学习笔记」树状数组
CVPR2021 行人重识别/Person Re-identification 论文+开源代码汇总
2022-2023 年十大应用程序发展趋势
Learning notes tree array
Open source huizhichuang future | 2022 open atom global open source summit openatom openeuler sub forum was successfully held
Server online speed measurement system source code
什么是WordPress
Technology sharing | quick intercom integrated dispatching system
"Node learning notes" koa framework learning
Two point, three point, 01 point plan [bullet I]
小水滴2.0网站导航网模板
Embrace open source guidelines
outlook突然变得很慢很卡怎么解决
Blackboard cleaning effect shows H5 source code + very romantic / BGM attached
go status. Go status code definition