1. Practice: User CRUD#
Script to implement the following functions
====================
1. Add user and set password
2. Delete user
3. View user
4. Exit
====================
If the input is not 1-4, give a prompt and if exit is not input, it can loop to add.
Press 1 to add user and set password: useradd passwd
Press 2 to delete user: userdel -r
Press 3 to view user: id
Press 4 to exit: exit
=====================================================================
Example 1:
--------------------------------------------------------------------------------------------
menu(){ # (Note: function)
echo "===================="
echo "1. Add user and set password"
echo "2. Delete user"
echo "3. View user"
echo "4. Exit"
echo "===================="
read -p "Please select the service you need:" ser
}
-------------------------------------------------
create_user(){ # (Note: function)
read -p "Create username:" user1
id $user1 &>/dev/null && echo "User already exists!" && return # (Note: exit function, use return)
useradd $user1 &>/dev/null # (Note: import to black hole)
id $user1 &>/dev/null || return # (Note: user exists, using id is better for judgment. Non-zero return value may indicate command execution error)
read -s -p "Set password:" passwd1 # (Note: -s hides the password)
echo $passwd1|passwd $user1 --stdin &>/dev/null
}
-----------------------------------------------------------
while :
do
menu # (Note: call function)
case $ser in
1)
clear # (Note: clear screen)
create_user
;;
2)
# ……………………………………
4)
echo "Exiting!"
exit
;;
*) # (Note: represents all other options, matching from top to bottom)
echo "Please enter 1-4!"
esac
done
-----------------------------------------------------------------------------------------------------------
Example 2: if syntax
---------------------------------------------------------------------
if ["$options"==1]||["$options"==2]||["$options"==3]||["$options"==4]
then
case $options in
1)
read -p "Please enter username:" username
if id $username &>/dev/null
then
echo "$username exists!"
else
read -s -p "Please set password:" password
useradd $username &>/dev/null
echo $password | $username --stdin &>/dev/null
echo -e "\n Created $username successfully!"
fi
;;
# ……………………………………………………
4)
echo "Exiting!"
exit
esac
else
echo "Please enter number 1 or 2 or 3 or 4!"
fi
Supplement: && can connect 2 commands
--------------------------------------------------------------------
&& can connect 2 commands
[root@sanchuang-linux ~]# id chen222
uid=1017(chen222) gid=1017(chen222) groups=1017(chen222)
[root@sanchuang-linux ~]# id chen222 && echo "chen222 exists"
uid=1017(chen222) gid=1017(chen222) groups=1017(chen222)
chen222 exists
[root@sanchuang-linux ~]# id chen222 &>/dev/null && echo "chen222 exists"
chen222 exists
# Note: it is better to use id to check if the user exists. A non-zero return value may indicate command execution error
2. Variables#
Variables Global/Local
Shell#
Variables defined in Shell are global by default
===========================================================================================
local a=10 Local variable
Example 1: local local variable
--------------------------------------------------------------------------------------------
func01(){
local a=10
}
func01 # (Note: call function)
echo $a
--------------------------------------------------------------------------------------------
[root@sanchuang-linux chenpeng]# sh aaa.sh
# (Note: empty. Local variable)
===========================================================================================
Example 2: Default global variable
--------------------------------------------------------------------------------------------
func01(){
a=10
}
func01 # (Note: call function)
echo $a
[root@sanchuang-linux chenpeng]# sh aaa.sh
10 # (Note: global variable)
Python#
Variables defined in Python are local by default
===========================================================================================
global a Global variable
Example 1: global a Global variable
--------------------------------------------------------------------------------------------
def func01():
global a # (Note: global variable)
a = 10
func01()
print(a)
[root@sanchuang-linux ~]# python3 python_function.py
10
===========================================================================================
Example 2: Default local variable Variables that can only be used within the function body
--------------------------------------------------------------------------------------------
def func01():
a = 10
func01()
print(a)
[root@sanchuang-linux ~]# python3 python_function.py
Traceback (most recent call last):
File "python_function.py", line 5, in <module>
print(a)
NameError: name 'a' is not defined # (Note: local variable)
Passing parameters in Shell functions (Positional Variables)#
Passing parameters in Shell functions (Positional Variables)
Example:
--------------------------------------------------------------------------------------------
Passing parameters in Shell
func01(){
a=100
echo "$1 $2 $3" # (Note: function parameters [positional variables])
}
func01 First parameter Second parameter Third parameter # (Note: calling parameters)
echo $a
Passing parameters in Python#
Passing parameters in Python
Example: Passing parameters in Python
--------------------------------------------------------------------------------------------
def func01(x,y):
global a
a = 10
func01(1,2)
print(a)
3. test#
test judgment is equivalent to []
Example: test
--------------------------------------------------------------------------------------------
[root@sanchuang-linux chenpeng]# a=123
[root@sanchuang-linux chenpeng]# b=123
[root@sanchuang-linux chenpeng]# test a==b
[root@sanchuang-linux chenpeng]# test a==b && echo ok
ok
4. Judgment methods [] [[]] (()) test#
Judgment methods [] [[]] (()) test
- (( )) Judges numbers > < == !=
- [[ ]] Judges strings or -eq -ne -gt -lt for judging numbers
- Some syntax [ ] is not supported, it is recommended to use [[ ]]
- test (test) judgment, equivalent to one bracket
Example: test
---------------------------------------------------------------------
[root@sanchuang-linux ~]# a=123
[root@sanchuang-linux ~]# b=123
[root@sanchuang-linux ~]# test a==b && echo ok
ok
[root@sanchuang-linux ~]# test a==b && echo ok || echo error
ok
5. Connection operations#
Connection operations
Use semicolon (;) to write multiple statements in one line
Example:
--------------------------------------------------------------------------------------------
[root@sanchuang-linux chenpeng]# echo "abc";echo "xyz"
abc
xyz
6. Functions#
Function definition/usage#
Example
--------------------------------------------------------------------------------------------
add(){
echo "The sum of two numbers is: $(( $num1 + $num2 ))"
}
add
============================================================================================
Function parameter passing#
Example: Positional parameter passing
--------------------------------------------------------------------------------------------
func01(){
a=100
echo "$1 $2 $3"
}
func01 First parameter Second parameter Third parameter
echo $a
============================================================================================
·Variable definitions inside functions are by default global variables
·Using the local keyword can convert to local variables
7. seq#
seq command
The seq command is similar to the range function in Python
Purpose: Print a sequence of ordered numbers
Format: seq [options] range of numbers
-s: Specify separator
-w: Specify equal width output
----------------------------------------
Display of number range:
[start] [step] end
Both start and step are optional
If step is positive, it indicates output from small to large
If step is negative, it indicates output from large to small
Example 1: [start] [step] end
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# seq 3 -1 1 # Note: the middle is the step. The sides are the starting positions
3
2
1
[root@sanchuang-linux ~]# seq 1 2 6
1
3
5
[root@sanchuang-linux ~]# seq 1 -2 6 # Note: when the step is negative, there is no output from 1 to 6
[root@sanchuang-linux ~]# seq 6 -2 1
6
4
2
Example 2: # seq 2 5 # seq -w 9 12
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# seq 2 5
2
3
4
5
[root@localhost ~]# seq -w 9 12 # -w specifies equal width output
09
10
11
12
============================================================================================
Supplement: Get the return result of the command
·Use backticks ``
·Or $()
Example 3: Get the last line of /etc/passwd and assign it to a variable
[root@sanchuang-linux ~]# tail -n1 /etc/passwd # Note: get the last line # tail -n1
wtc:x:1029:1029::/home/wtc:/bin/bash
[root@sanchuang-linux ~]# line=`tail -n1 /etc/passwd` # Note: Method 1
[root@sanchuang-linux ~]# echo $line
wtc:x:1029:1029::/home/wtc:/bin/bash
[root@sanchuang-linux ~]# line1=$(tail -n1 /etc/passwd) # Note: Method 2
[root@sanchuang-linux ~]# echo $line1
wtc:x:1029:1029::/home/wtc:/bin/bash
============================================================================================
Example 4: seq command is similar to the range function in Python
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# vim seq_test.sh
for i in `seq 2 10` # Note: backticks execute this command to get the return value of the command
do # Note: seq 2 10 includes 2 and 10
echo $i
done
-----------------------------------------------------------------------
for i in $(seq 2 10) # Note: also indicates executing this command to get the return value of the command
do
echo $i
done
[root@sanchuang-linux ~]# bash seq_test.sh
2
3
4
5
6
7
8
9
10
============================================================================================
Example 5: -s: Specify separator
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# seq -s "+" 10 # -s: specify separator
1+2+3+4+5+6+7+8+9+10 # Note: does not start with, by default starts from 1 to 10
[root@sanchuang-linux ~]# seq 10 # Note: by default the connector is a newline character
1
2
3
4
5
6
7
8
9
10
8. Practice: Create User#
Create user (3 retry opportunities) script
Example: seq command create failure retry
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# vim user_add.sh
#!/bin/bash
# Add # Note: user addition part
add(){
for i in `seq 3 -1 1` # Note: seq command is similar to python range function 3 2 1
do
echo "Adding user"
read -p "Please enter username:" username
id $username &>/dev/null && echo "User already exists, you have $(( $i - 1)) chances left" && continue
#if id $username &>/dev/null
#then
# echo "User already exists, you have $(( $i -1 )) chances left"
# continue
#fi
#useradd $username &>/dev/null && echo "Created successfully!" && echo $password | passwd $username --stdin &>/dev/null && break || echo -e "\nCreation failed!"
if useradd $username &>/dev/null
then
echo "Successfully created ${username}!"
read -s -p "Please set password:" password
echo $password | passwd $username --stdin &>/dev/null
break
else
echo "Creation failed! You have $(($i-1)) chances left!"
fi
done
}
# Delete
del(){
echo "Deleting user"
read -p "Please enter username:" username
userdel -r $username &>/dev/null && echo "Deleted successfully!" || echo "User does not exist, deletion failed!"
}
# View
seek(){
echo "Viewing user"
read -p "Please enter username:" username
id $username
}
echo "#############################"
echo "Press 1 to add user and set password"
echo "Press 2 to delete user"
echo "Press 3 to view user"
echo "Press 4 to exit"
echo "#############################"
while :
do
read -p "Please enter your choice:" options
case $options in
1)
add
;;
2)
del
;;
3)
seek
;;
4)
echo "Exiting!"
exit
;;
*)
echo "Please enter specified content 1-4!"
esac
done
9. Loop to get the content of files or command output (3 methods)#
Redirection#
Example 1: Redirection while read a b c; < a.txt
--------------------------------------------------------------------------------------------
#!/bin/bash
while read a b c
do
echo "name is $a, sex is $b, age is $c "
done < a.txt # Note: file in the current path. Can accept absolute path
============================================================================================
Pipe#
Example 2: Pipe cat a.txt | while read a b c
--------------------------------------------------------------------------------------------
cat a.txt | while read a b c
do
echo "name is $a, sex is $b, age is $c "
done
============================================================================================
For loop#
Example 3: For loop (Note: using for loop is not very good)
#For loop defaults to split by whitespace (space/newline/tab)
--------------------------------------------------------------------------------------------
echo "For loop implementation..........."
for i in `ls` # i represents each file output by whitespace
do
echo $i
done
--------------------------------------------------------------------------------------------
Example 3.2: i represents each item of the file, split by whitespace
[root@sanchuang-linux ~]# vim file_test.sh
for i in `cat a.txt`
do
echo $i
done
[root@sanchuang-linux ~]# bash file_test.sh
wenyao
f
18
chenpeng
m
19
wtc
f
17
[root@sanchuang-linux ~]# cat a.txt
wenyao f 18
chenpeng m 19
wtc f 17
Example 3.3: for i in `ls -al` # i represents detailed information under the current directory, i represents each item split by whitespace
10. Practice: Find the lines in list.xml where the host is ZF and then loop to output the relationship between ip and the server#
Find the lines in list.xml where the host is ZF and then loop to output the relationship between ip and the server
Example
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# cat list.xml
####IP Hostname Server#########
127.0.0.1 ZF-1 1 33 49 57
127.0.0.1 ZF-11 65 67 69
127.0.0.1 HF-1 22 34 6
127.0.0.1 HF-11 6 17 36
127.0.0.1 ZF-12 1 2
127.0.0.1 HF-1 34 7
--------------------------------------------------------------------------------------------
Step 1: First filter out the lines where ZF is located
[root@sanchuang-linux ~]# vim test6.sh
#!/bin/bash # Pipe | sends output as input to the next command
cat list.xml |grep ZF |while read ip host qufu # First filter out the lines where ZF is located
do # while read gets the content
echo "ip:$ip, server:$qufu" # Note: parameter 3 is assigned to $qufu
done
[root@sanchuang-linux ~]# cat list.xml | grep ZF
127.0.0.1 ZF-1 1 33 49 57
127.0.0.1 ZF-11 65 67 69
127.0.0.1 ZF-12 1 2
[root@sanchuang-linux ~]# sh test6.sh # Note: $ip $host $qufu do not necessarily need to correspond
ip:127.0.0.1, server:1 33 49 57 # The first two correspond, taking both
ip:127.0.0.1, server:65 67 69 # If there are more, it will all be the latter content
ip:127.0.0.1, server:1 2 # If there is none, it will be empty (if not obtainable, it will be empty)
--------------------------------------------------------------------------------------------
Step 2: Wrap a loop
#!/bin/bash
cat list.xml |grep ZF |while read ip host qufu
do
for i in $qufu # Note: wrap a loop. For loop splits by space
do
echo "ip:$ip, server:$i" # Note: here is i. Loop through the server
done
done
[root@sanchuang-linux ~]# sh test6.sh
ip:127.0.0.1, server:1
ip:127.0.0.1, server:33
ip:127.0.0.1, server:49
ip:127.0.0.1, server:57
ip:127.0.0.1, server:65
ip:127.0.0.1, server:67
ip:127.0.0.1, server:69
ip:127.0.0.1, server:1
ip:127.0.0.1, server:2
11. Loop to get the content of files or command output#
Loop to get the content of files or command output
-
for i in defaults to split by whitespace to loop through each element
-
while read gets each line
The parameters of while read can accept any number, but still split by whitespace by default
If the parameters do not correspond to the obtained values, then the parameters will be empty
If the number of parameters split by whitespace in the file is greater than the parameters accepted by read, the extra parameters will all be assigned to the last read accepted parameter
Pipe is a way of communication between processes
12. One-dimensional arrays in shell#
One-dimensional arrays in shell
One-dimensional arrays in shell use
Definition: Use parentheses
, with spaces
as separators
Blog link: https://www.cnblogs.com/tangshengwei/p/5446315.html
Example 14.1: Definition, Access
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# a=(xx yy zz) # Note: a is an array
[root@sanchuang-linux ~]# a=(xx yy zz ff) # Note: a is an array
[root@sanchuang-linux ~]# echo ${a[0]} # Note: access by index, index starts from 0
xx
[root@sanchuang-linux ~]# echo ${a[1]} # Note: access by index
yy
[root@sanchuang-linux ~]# echo ${a[3]}
ff
[root@sanchuang-linux ~]# echo ${a[@]} # Note: ${a[@]} means each number inside, @ takes all values inside
xx yy zz ff # Note: $@ takes all content in the parameter list
[root@sanchuang-linux ~]# echo ${a[@]:1:4} # Note: access (slicing)
yy zz ff
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# a=(xx yy zz ff)
[root@sanchuang-linux ~]# echo $a # Note: echo $a only takes the first element in the array
xx
[root@sanchuang-linux ~]# echo ${a[*]} # Note: ${a[*]} takes all content in the one-dimensional array, same effect
xx yy zz ff
[root@sanchuang-linux ~]# echo ${a[@]} # Note: ${a[@]} takes all content in the one-dimensional array
xx yy zz ff
[root@sanchuang-linux ~]# echo ${a:0:4} # Note: slice the character xx starting from 0
xx
[root@sanchuang-linux ~]# echo ${a:1:4} # Note: slice the character xx starting from 1
x
[root@sanchuang-linux ~]# echo ${a[*]:1:3} # Note: access, same effect (slicing)
yy zz ff
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# a=(1 2 3 4)
[root@sanchuang-linux ~]# echo ${a[*]:1:3} # Note: access, closed interval (slicing)
2 3 4
============================================================================================
Get length (number of elements)
# Note: $# gets the length of the parameter list
# echo ${#a[*]}
# echo ${#a[@]}
Example 14.2: Get the length of a one-dimensional array (number of elements)
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# echo ${#a[*]} # Note: cannot use $a directly to get, because $a represents the first element inside
4
[root@sanchuang-linux ~]# echo ${#a[@]}
4
[root@sanchuang-linux ~]# echo ${#a} # Note: length of the first element
2
###########################################################################################
Example 14.3: Get string length echo ${#b}
[root@sanchuang-linux ~]# b=abc
[root@sanchuang-linux ~]# echo ${#b}
3
============================================================================================
Modify/Delete elements (modification/deletion of one-dimensional arrays in shell)
Example 14.4: Modify/Delete elements
[root@sanchuang-linux ~]# echo ${a[*]}
xx yy zz ff
[root@sanchuang-linux ~]# a[3]="hh" # Note: modify element
[root@sanchuang-linux ~]# echo ${a[*]}
xx yy zz hh # Note: clear array unset a
[root@sanchuang-linux ~]# unset a[3] # Note: delete specified element (index 3)
[root@sanchuang-linux ~]# echo ${a[*]}
xx yy zz
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# echo ${a[*]}
xx zz
[root@sanchuang-linux ~]# unset a[1] # Note: cannot delete
[root@sanchuang-linux ~]# echo ${a[*]}
xx zz
[root@sanchuang-linux ~]# echo ${!a[*]} # Note: add ! to see the index of the elements
0 2 # Note: after deletion, the index will not be reallocated. Each value initially corresponds to an index, which will not change
[root@sanchuang-linux ~]# unset a[2] # Note: delete the zz element, unset a[2], index 2
[root@sanchuang-linux ~]# echo ${a[*]}
xx
[root@sanchuang-linux ~]#
13. Generate random numbers in linux#
Generate random numbers in linux
Example
--------------------------------------------------------------------------------------------
[root@sanchuang-linux ~]# echo $RANDOM # Note: custom environment variable
15386
[root@sanchuang-linux ~]# echo $RANDOM
24960
############################################################################################
Knowledge Point 15.2 Generate random numbers within a specified range
Example 1: Generate random numbers within 10 (excluding 10)
[root@sanchuang-linux ~]# echo $(($RANDOM % 10))
1
[root@sanchuang-linux ~]# echo $(($RANDOM % 10))
8
[root@sanchuang-linux ~]# echo $(($RANDOM % 10))
2
[root@sanchuang-linux ~]# echo $(($RANDOM % 10))
3
14. Practice: Write a program to randomly select classmates to sing, if they have sung, they cannot be selected again#
Write a program to randomly select classmates to sing, if they have sung, they cannot be selected again
-
Write a file that contains the names of our singers name.txt
-
Randomly select a singer # 1. Loop selection 2. Discard once selected
============================================================================================
# Note: Use the output of the command with `` backticks
# Note: Turn the read personnel list into an array
Example
--------------------------------------------------------------------------------------------
[root@sanchuang-linux chenpeng]# vim singer_test.sh
#!/bin/bash
# Read the content of name.txt # Note: backticks ` ` put the output of the cat command into the array
singers=(`cat name.txt`) # Note: put the read content into the array (cat reads)
echo ${singers[@]} # Note: verify if the data is retrieved # Note: relative path refers to the file in the current directory
# How many people
total=${#singers[@]} # First get the number of people (count the length of singers)
for i in `seq $total` # Then loop (for loop times, loop through the number of $total people)
do # Note: backticks ` ` execute the command
read -p "Press any key to draw" # Note: read purpose: press a key to continue the loop
# Randomly select a person to sing # Each loop draws a new person from the list (due to index issues)
random_num=$(( $RANDOM % ${#singers[*]} )) # Note: generate a random number, range 0 ~ length of one-dimensional array
echo "Random number is: $random_num" # Note: randomly select index
echo "Please welcome ${singers[$random_num]} to sing a song! Everyone give a warm welcome!"
unset singers[$random_num] # Note: delete the selected person (unlike python, deletion does not change the index)
singers=(`echo ${singers[@]}`) # Note: solution reassigns, assigns to a new one-dimensional array
echo "The specific list of non-singers is: ${singers[@]}" # Note: ↑ can also use singers=(${singers[@]})
done # Note: ↑ can also use singers= `echo ${singers[@]}`
[root@sanchuang-linux chenpeng]# cat name.txt # Note: ↑ after reassigning, the index will change from 0 to total length
fengcheng
zhanghuayou
pengyifan
chenpeng
xulilin
tangliangfei
wangtiancheng
lixinhai
liangluyao
--------------------------------------------------------------------------------------------
Demonstration
[root@sanchuang-linux chenpeng]# sh singer_test.sh
fengcheng zhanghuayou pengyifan chenpeng xulilin tangliangfei wangtiancheng lixinhai liangluyao
Press any key to draw
Random number is: 2
Please welcome pengyifan to sing a song! Everyone give a warm welcome!
The specific list of non-singers is: fengcheng zhanghuayou chenpeng xulilin tangliangfei wangtiancheng lixinhai liangluyao
Press any key to draw
Random number is: 2
Please welcome chengpeng to sing a song! Everyone give a warm welcome!
The specific list of non-singers is: fengcheng zhanghuayou xulilin tangliangfei wangtiancheng lixinhai liangluyao
# Note: When obtaining command output, add `` backticks
15. Practice: Generate random numbers between 5 and 10#
Generate random numbers between 5 and 10
Generate random numbers between 5 and 10
[root@sanchuang-linux chenpeng]# echo $(( $RANDOM % 10 )) # Note: generate random numbers within 10
3
[root@sanchuang-linux chenpeng]# echo $(( $RANDOM % 5 +5 )) # Note: take random numbers within 5 +5
6
[root@sanchuang-linux chenpeng]# echo $(( $RANDOM % 5 +5 ))
8
--------------------------------------------------------------------------------------------
Random numbers between 50 and 150
[root@sanchuang-linux chenpeng]# echo $(( $RANDOM % 100 +50 ))
79 # Note: 100 is the absolute value of the interval, 50 is the initial value
--------------------------------------------------------------------------------------------
Random numbers between 150 and 200 # Note: 150 initial value, 50 + 150 end value
[root@sanchuang-linux ~]# echo $(( $RANDOM % 50 + 150 )) # Note: between 150~200
190
16. tr (replace command)#
tr command (replace command)
The tr command (mainly used for character replacement) # Note: commonly used for text processing
- Character conversion tool
- Can only operate on
stdin
, cannot operate directly on files # Note: can only operate on standard input
----------------------------------------------------
Using tr to convert characters
- tr SET1 SET2
- Replace characters in SET1 with characters in SET2 at the same position
tr -d Delete specified characters
tr -s Compress the same characters, compressing consecutive specified characters into one character
Example
--------------------------------------------------------------------------------------------
Example 1: Replacement
# Note: replace at the same position
[root@sanchuang-linux chenpeng]# echo 123456| tr 345 xyz # Note: replace 345 with xyz
12xyz6 # Note: can only operate on standard input
[root@sanchuang-linux chenpeng]# echo 123456| tr 3 xyz # Note: replace 3 with xyz
12x456 # Note: only replaced x, at the corresponding position
# Note: replace as many positions as there are characters
# Note: replace at the same position
============================================================================================
Example 2: Delete # echo 123456| tr -d 34
tr -d Delete specified characters
[root@sanchuang-linux chenpeng]# echo 123456| tr 3 "" # Note: "" cannot be empty, it must replace at the same position
tr: When not truncating set1, string2 cannot be empty
[root@sanchuang-linux chenpeng]# echo 123456| tr -d 34 # Note: delete using tr -d
1256
============================================================================================
tr -s Compress the same characters, compressing consecutive specified characters into one character
Compress consecutive specified characters into one character
Example 3: tr -s Compress the same characters
[root@sanchuang-linux chenpeng]# echo 111223333444445556666| tr -s 34
11122345556666 # Note: when there are consecutive, compress into one
[root@sanchuang-linux chenpeng]# echo 11122333344444555666633377744| tr -s 34
1112234555666637774 # Note: not deduplication
============================================================================================
Exercise 4: Replace : in the environment variable with a space # Note: key point tr cannot replace file content
[root@sanchuang-linux chenpeng]# echo $PATH |tr ":" " " # Note: key point tr receives standard input
/lianxi/sc /usr/local/sbin /usr/local/bin /usr/sbin /usr/bin /root/bin /usr/local/nginx/sbin /root/bin /usr/local/nginx5/sbin /root/bin
============================================================================================
Extension 5: Replace the content in a file, generating a new file
# Note: import the file for standard input
Example: Replace : with a space in /etc/passwd
--------------------------------------------------------------------------------------------
Writing method 1: import with cat
[root@sanchuang-linux chenpeng]# cat /etc/passwd |tr ":" " " >/tmp/passwd
[root@sanchuang-linux chenpeng]# less /tmp/passwd # Note: : all changed to space
Writing method 2: tr receives standard input Redirect standard input tr ":" " " </etc/passwd
[root@sanchuang-linux chenpeng]# tr ":" " " </etc/passwd >/tmp/passwd2
[root@sanchuang-linux chenpeng]# less /tmp/passwd2 # Note: : all changed to space
# Note: Writing method 2 imports a file for standard input tr ":" " " </etc/passwd
============================================================================================
Extension 5.1 Redirect standard input
[root@sanchuang-linux chenpeng]# wc -l /etc/passwd # Note: wc -l view file line count
52 /etc/passwd
Example: Redirect standard input
[root@sanchuang-linux chenpeng]# wc -l < /etc/passwd
52