Teaching Wife to Learn Common Command Guidelines for Linux Operations and Maintenance

Teach your wife to learn Linux (two) Linux frequently used command Guide

Author: Yao Maomao's blog

tips: The article is too long, and it is sent out in two chapters. The first three chapters are: 1. File and directory operation; 2. File viewing and editing; 3. File searching and statistics.


I. overview

1.1 Write in the front-Learning Guide

The purpose of this paper is mainly as a learning map for beginners to learn Linux.

So I will only talk about some of the commands and operations that are commonly used in our production process, and I will not even talk about the partial usage of commands in this article.

For detailed instructions on Linux commands, you can refer to the website.

In the words of the Entity Book, I recommend "Learning linux Operations and Maintenance with Old Boys - Core System Command Practice".

1.2 Overview of Common Commands

I classify common commands under Linux into several categories:

1. File and directory operations

2. File Viewing and Editing

3. Document Search and Statistics

4. File decompression and compression

5. User and File Permissions

6. Resource Monitoring and Management

Why are the chapters of a column related to documents?

Because everything in Linux is a file, cpu, memory, disk, peripherals, drivers and so on, all exist in the form of files in our Linux system.

1.3 Common shortcuts

There are several shortcuts for my command under Linux. Basically, we will use them all the time when dealing with Linux, that is:

enter executes the command. enter the command and remember to return before it takes effect.

tab automatic completion. When writing folder paths, type the initials to complete the subsequent names directly, and when you encounter folders with the same initials, the list will be displayed.

_Using the up key of the direction key, you can retrieve the last command executed, and you can always look up the history command to see all the history commands using the history command.

ctrl + c interrupt command. Use this command when executing commands on linux is stuck, error, etc. It can't be executed and can't exit.

ctrl + z interrupt command. Typically, this command can be tried when ctrl + c cannot interrupt.

ctrl + insert replication. Copy the selected content.

shift + insert paste. Paste the contents of the shear board.

ctrl + Backspace deleted forward.
Sometimes Backspace cannot delete a character when entering a command. It is input as a character itself. Use this command to do Backspace deletion.

delete is deleted backwards.

In addition, there are two useful commands when viewing scrolling files, which are usually used when viewing log files:

ctrl + s stop scrolling

ctrl + q restore scroll screen

1.4 Help Order

Man's omni-directional help command is used in the form of man [command], such as

man ls

Use: q command to exit the help interface

Help commands are commonly used in the form of [commands] -- help, such as

ls --help

There are some other uses for the commands in this article, which you can explore by yourself.

1.5 History Command View

# View commands that have been typed

linux commands that have been typed out can be turned up and down with the direction keys.

1.5 Notes

1. This article uses the Linux environment centOs 7, and other distributions may have slight inconsistencies. The same is true of the Mac command line.

2. All commands in linux should be separated by spaces, such as cd xx files, which should be paid attention to in the second chapter.

3. Commands generally have parameters. man or help can be used to view their parameters. The parameter is usually written as - beginning. For example, ls-l looks at all files in the current directory. Rm-f xxx file, delete xxx file, -f parameter means that if there is no file, it is not prompted.

Common orders

2.1 File and Directory Operation

2.1.1 good friends of path switching: cd, ls, ll, pwd

In linux, the cd command is always our little partner. It is also the king's command for all basic operations, instead of giving you a past cd, but a path switch, that is, Change Directory.

ls and ll are good companions with cd, which can be used to see what files and directories are under the current folder. Why can it be so cock? Because they are list s, understand.

Why is ll also a list? Because it's the vest of ls-l.

If cd goes to cd, it is already unknown in the clouds, not knowing the true colors of Mount Lu, and using pwd to look at the fan path, and to see its absolute path, that is, Print Working Directory.

The following is a brief explanation of the order:

cd /
# Enter the host root directory

cd ~
# Enter the user root directory

cd ..
# Return to Dad (Superior) Catalogue

cd ../..
# Return to the directory of grandpa (superior), and so on.

cd -
# Return to the last directory

cd /yaomaomao/wfy/123/456
# Using absolute paths, start with the root directory and find the 456 directory layer by layer. / For the root directory
# Horizontal display of all files and directories in the current directory

ls -a 
# Display the contents displayed by the hidden file + ls command 

ls -l
# Equivalent to ll, the LL command is usually used directly.

# Vertical display of all files and directories under the current directory, and permission information
ll -a
# Display the contents displayed by the hidden file + ll command

ll -h
# Convert file size from unit bit to appropriate unit display, such as kb, Mb, Gb, according to actual size.
# - The parameter h is very useful in linux. It can be used in almost all commands that need statistical size, such as df-h, du-h, free-h.

# View the current path
2.1.2 Files Create Good Partners: touch, mkdir

In linux, there are many ways to create files, but touch is the most concise one. With a touch, an empty file is created.

To create a directory, it's mkdir, make directory.

touch wfy.txt
# Create a wfy.txt empty file in the current directory

touch /var/www/yaojiaxiaoyuan{01..10}.html
# Bulk Creation of Empty Files

mkdir [Directory name]
# Create an empty directory in the current directory

mkdir yaomaomao wfy 123 456
# Create multiple directories at the same time, separated by spaces, and create multiple directories at the same level

# If you want to create a multi-level subdirectory, use mkdir-p below.

mkdir -p /yaomaomao/wfy/123/456
# Multilayer directories are created at the same time. Yaomaomao directory is created in the current directory at one time, wfy directory is created in the yaomaomao directory, 123 directory is created in the wfy directory, and 456 directory is created in the 123 directory.

Created successfully using mkdir-p/yaomaomao/wfy/123/456. Do you remember the above command? cd go in and have a look.

cd yaomaomao/wfy/123/456

Then pwd looks at the path, and then touch es a file to see

touch yaomaomao.txt

# Check to see if the creation was successful
2.1.3 Copy, Move and Delete: cp, mv, rm

This CP is not the other "CP", because we are not capitalized. Dinner girl please go away, we are just the abbreviation of copy.

mv is move. That's understandable.

Rm, as its name implies, is remove lo. Of course, use this command with caution. Especially don't use rm-rf/*. If you can't resist hitting this command, ok, wait for the system to be reinstalled.

cp [File name to be copied] [File name after copy]
# Copy the former and turn it into the latter.

cp [to-be-copied directory] [target directory]
# Copy the former and turn it into the latter. This is true of files and directories.
# But sometimes there are subdirectories in the directory. This command doesn't work. You have to use the following command, cp-r/R.

Cp-r [to-be-copied directory] [target directory]
What does -r/R mean? That is, recursion. Find all subdirectories in the current directory indefinitely. Dump it all and copy it to the target path.

mv [file name to be copied] [file name after copy]
# Change the filename of the former to the filename of the latter

mv [mobile directory] [target directory]
# Change the filename of the former to the filename of the latter

Okay, after cp and mv, let's take a look at rm. RM Code of Use:

Never use asterisks alone, let alone slashes to add stars /.

Never use asterisks alone, let alone slashes to add stars /.

Never use asterisks alone, let alone slashes to add stars /.

Say the important thing three times.

Common commands are as follows

rm [file name]
# Delete files. There will be an error message if the file does not exist.

rm -f [file name]
# Delete files. - f. Ignore information and do not prompt.

rm -rf [Directory name]
# Remove directories recursively

rm -rf [Document 1] [Document 2] [Directory 1] [Directory 2]
# Delete multiple files and directories

rm -rf *.log
# Delete all files at the end of the. log suffix in the current directory

rm -i *.log
# When deleting all log files, you will be asked one by one. This command is not usually used, but it may be needed in some cases.
# When inquiring, press y to confirm deletion, n does not delete.

- The r/R parameter, remember the cp-r/R above, is also a recursive deletion.

2.2 File Viewing and Editing

2.2.1 Good helper for merging files: cat
cat [filename]
# Output all contents of the file to the screen

cat [file 1] [file 2]
# Output all contents of file 1 and file 2 to the screen

cat [file 1] [file 2] > [file 3]
# Combine file 1 and file 2 and output them to file 3. If there is no file 3, a new file 3 will be generated automatically.

Cat-n [filename]
# Line numbers are added to output file contents

Cat-A [filename]
# Display all hidden characters when output file content

Cat is characterized by a one-time output of all content to the screen. One of the most frequently used functions of cat is to merge files and output them to new files. Because there are many other tools to view if you just view them.

In addition, the cat command is commonly used with the pipe character "|". The input used as a pipe character, such as cat xxx.log | grep'I'm looking for this word', will be discussed later when looking for a file.

2.2.2 Observation log expert: tail

tail is commonly used to view log usage and display the latest additions to a file

tail -f xxx.log
# Continuously append the last 10 lines of the log file

tail -fn1000 xxx.log
# Add the - n parameter and keep appending the last 1000 lines of the log file

tail can also display multiple file contents at the same time, but it is not recommended, such as

tail -fn1000 xxx.log xxx2.log

If more than one file is displayed, a file name title is added before each file displayed.

[tail -fn1000 xxx.log xxx2.log](D:\ technical data notes) teaching wife learn Linux\2\tail -fn1000 xxx.log xxx2.log.png)

In contrast to tail, there is also a head, which displays the contents of the file from the beginning. The general usage is head-n [filename], which is similar to tail.

2.2.3 Editing documents I am good at: vi/vim

To say what the most powerful editor in linux is, 10 of 10 people would say vim.

So, what's the difference between VI and vim? Well, actually, there's no difference. VIM is an enhanced version of vi. Like black and white with VI, like the color of the VIM will do.

vim can be used against the weather, but it's just a tool. It doesn't need to be a geek. Just know some common commands.

Okay, let's use vim [filename] to enter the file first.

vim has several modes, namely normal mode, editing mode and command mode.

Oh, there is also a visual mode, not often used, normal mode can enter according to v, no use.

Normal mode, as its name implies, is normal mode. I prefer to call it stateless mode. When using vi/vim [file] to enter a file, the default mode is this mode. After entering other modes, you can use the Esc key to return to this mode.

vim [filename]
# enter normal mode by default

In normal mode, press i, a, o, s and enter editing mode. Usually, the frequency of use is in this order. In the edit mode, the input content is no different from the operation of opening the tablet board under our windows.

# insert, cursor inserted before the current character

# Appnd, insert the cursor after the current character

# Next line insert

# Not often used. Delete the current character and insert it

In addition, there are several key capitalization modes I, A, O, S in editing mode, which are not commonly used and can be explored by oneself.

Cursor movement

# Move to the left

# Downward movement

# Upward movement

# Move to the right

ctrl + f
# Page down

ctrl + b
# Page up

# The head of a row

# End of line

# Space key, move a character down. The difference with the left key () is that the left key () can only move in the line.

If it is inconvenient to move up and down the left and right direction keys, we can use h, j, k, l keys to operate left, down, up and right in normal mode.

Exit, save, use colon (:) in normal mode to enter bottom command mode

# Exit not saved

# Mandatory Exit without Preservation

# Exit save

# Forced Exit Preservation

You may have found that in vim, exclamation marks (!) mean coercion.

The basic operation of the text is finished. If vim is just like that, it will not be the title of the most powerful text editor on linux. Now let's talk about some shortcuts to improve the efficiency of our text manipulation.

Some shortcuts in normal mode

# Capital g, move to the end of the article.

# n, number, line number. 100G moves to line 100. 1G is the first.

# Move to the header. The same effect is 1G.

# They represent high, middle and low respectively, that is, moving the top, middle and bottom of the current screen page.
# Delete the current line, you can continue to press d to delete.

# n, number, line number. ndd, delete the current line and how many lines after it, such as 100dd, delete the current and subsequent 100 lines
# Undo the operation. If the above deletion using dd is wrong, you can press u to cancel. Revocation in editing mode needs to enter normal mode according to Esc and revoke by U.

//Enter replication mode.

# Copy the current row.

# n, number, line number. Smart as you already know, like 16yy, is to copy the content of the current line to 16 lines.

# Paste the contents of the current vim clipboard.

# Commonly used combination keys, that is, after using yy copy above, can use p to paste immediately, or move to a designated location and press p, that is, paste the content just now.

# Selected copy. Look at this command, go to the beginning of the line, press y to enter the copy mode, then move the cursor to the end of the text, and then press p to paste. Of course, if your cursor has moved to the appropriate position, you can go directly to ggyGp.
# There is a flaw here, such copy content can only be pasted in vim, once out of vim, there is no such content in the clipboard. Then what shall I do? Look at this command.

# These two fully selected replicated commands take the content out of vim. Of course, it is not generally used, only in some special cases.

After moving, deleting, copying, pasting, and looking up. Input/or?, in normal mode.

# Look down for the string yaomaomao. Press n to keep looking down.

?Yao Mao Mao
# Look up for Yao Maomao. Press n to keep looking up.

# It will be interesting to cooperate with /,?, / n, keep looking down, / N, keep looking up,? + n, keep looking up,? + N, keep looking down.

Replacement is to enter the bottom line command mode, as mentioned above, which is to use a colon in normal mode: enter this mode.

# Global substitution, replacing old characters with new ones

If you do not want global substitution but specify the number of rows, you can use this command:


As shown in the figure below, replace lines 1 to 10 with Xiaoli.

What is the replacement from line N to the last line? Believe in wisdom, you should have thought of:


In addition, there are some interesting commands in command mode, such as:

:set number
# set number

:set nonumber
# set nonu

:set nu
:set nonu
# Ibid., nu is the abbreviation of number.

:set ff
# Looking at the file format, you may show foramt=dos. There may be some format problems in editing the file under windows and uploading it to linux. So you need to convert the text format, that is, the following command: set ff=unix

:set ff=unix
# Set the file format, ff is format, that is, the file is set to unix. You can set it and then use the: set ff command.

There are also commands such as split window and overload file.

Bottom line commands are certainly more than just a few, if you want to know more commands, you can refer to.

linux-vim tutorial for rookie tutorial https://www.runoob.com/linux/....

And the linux commands I just recommended https://man.linuxde.net/vi.

Finally, we summarize several modes of switching:

1. vi/vim [fileName] - > normal mode

2. Enter i, a, o, s keys under normal - > editing mode

3. Enter a colon under normal: --> Bottom Line Command Mode

4. Esc exits to normal mode

5,: q: wq: q!: wq! Exit without saving / saving files

Oh, there's also a normal input v into view mode, which in the future advanced learning can be said, generally useless.

2.2.4 vim brothers: more, less

After VIM, let's take a look at more and less. This is a good friend based on vim.

These two commands are similar to cat, but show reading page by page.

More can show percentages. Generally, more can be used to check the problem log from scratch.

less works wonderfully when viewing large files, which are said to be partially loaded into memory.

Let's see more first

more [filename]

More-f [filename]
# When adding the parameter f, the meaning of the - f parameter is to calculate the number of rows, it is based on the actual number of rows (some words with too long a single line are considered to be two or more lines).

As you can see, more opens the file to see the percentage of files you are currently viewing.

Using more to view files or logs, some shortcut commands can improve our efficiency:

Space key
 # Scroll down a screen, the effect of the f key is the same, but generally use the space bar, more convenient.

 # Scroll up a screen

# View the current line number

 # Output the current file name and line number

 # Quit more command, ctrl + c can also quit

If you don't use the - f parameter to view the command, you can try turning pages up and down with b and space, and you will find that the contents you view back and forth may be different. Because no - F is required to force the number of lines, some single-line words that are too long will be considered two or more lines.

There is also a command called "specify line view", that is:

more +[num] [filename]
# View what follows the specified line number

more -[num] [filename]
# Looking at the contents before the specified line number, this command is not generally used, mainly + num. This command, if used, is generally used as an export.

Example is

more +1000 after school.txt

more -1000 after school. txt

The advantage of less is that it doesn't load the entire file before viewing the file, so it works wonderfully when viewing large files. If the file is particularly large, such as over 1G, you can use less to improve efficiency.

less [filename]
# Basic View Command

Less-m [filename]
# Similar to more command, showing percentages

Less-N [filename]
# Display line number

Similar to the more command, less has the same shortcut key, but cannot exit with ctrl + c

# Exit less command

# Move down half screen

# Move up half screen

# Move down one line

# Move up a line

//Space key
# Scroll down a screen, the effect of the f key is the same, but generally use the space bar, more convenient.

# Scroll up a screen

# Output current file name and line number, percentage

: f
# Output current file name and line number, percentage

And less is not only more to view, but also a lookup command using the vi editor

/ [Find Characters]
# With the n key, check all from top to bottom

[Find Characters]
# With the n key, look down all

Remember vim's N and N, the same effect.

2.2.5 I am proud of plug-in and edit without opening the file:sed

File viewing and editing has finally reached the last section, this time to talk about the killer sed.

Using vim requires editing within the file, sometimes just adding a sentence or a parameter to the bottom of the file, which requires experience.

vim [file] - >

G (Move to the bottom) - >

o Add - > next line

shift + insert (insert content into clipboard) or self-editing

This whole set of steps is rather tedious.

Is there a lighter way?

Stream Editor, you deserve it.

Ps. Actually, there's an echo command that does the same thing.

echo "Additional Content" > [File Name]

Case study:

sed -i '$a I'm Yao Maomao.' After school utf-8.txt

The string "I am Yao Maomao" was added at the end of the document.

As shown in the picture:

So, would you like to append characters to the specified line or to the front or back of each line?

sed -i '20a Oh, I'm Yao Maomao 20 append' After school utf-8.txt
# Add "Oh, I'm Yao Maomao 20 append" on the next line of line 20 of the document [utf-8.txt after school]

As shown in the picture:

sed -i '20i Oh, I'm Yao Maomao 20 insert' After school utf-8.txt
# Insert "Oh, I'm Yao Maomao 20 insert" on line 20 of the document [utf-8.txt after school]

sed -i 'a I'm Yao Maomao. append' After school utf-8.txt
# Add "I'm Yao Mao append" to the file [utf-8.txt after school] next line of characters

sed -i 'i I am a monster. insert' After school utf-8.txt
# Insert "I am a demon insert" on each line of characters in the file [utf-8.txt after school]

So, there's a simple way to add characters.

sed -i '1i Oh, I'm Yao Maomao, at the beginning. insert' After school utf-8.txt
# It means inserting characters before the first line.

sed -i '9999a Oh, I'm Yao Maomao, at the end. append' After school utf-8.txt
# It means to append characters after line 9999.

All of the above is incremental. So what about adding, deleting and revising the deletion, revision and revision of the four brothers? Can sed also do that?

Looking at the above, let's first summarize the basic format of sed:

Sed [parameter options] [sed built-in command character update content] [input file]

Change, built-in command character s:

sed 's/book/books/' file
# Replace strings in text

sed -n 's/test/TEST/p' file
# - The n option is used with the p command to indicate that only those lines that have been replaced are printed.

sed -i 's/book/books/g' file
# The direct edit file option - i matches the first book in each line of the file and replaces it with books

Here we pay special attention to parameter -i, which means modifying the contents of files directly. If you don't use - i, you can try to verify that the output is only to the terminal, without actually modifying the file content.

As shown in the picture:


After adding some content to the first line of data with sed command, and then using cat to view the file, the content of the file has not changed.

Delete, built-in command character d:

sed '2d' wfy.txt
# Delete line 2. d is sed built-in command, 2 is line number

As mentioned above, if no - I is added, the deleted content is simply exported to the terminal without actually changing the file. So what about adding - i?

sed -i '2d' wfy.txt

See if line 2 has been deleted.

What if you want to delete multiple lines?

sed -i '1,3d' After school utf-8.txt
# Delete lines 1 to 3
sed -i '/\/sbin\/nologin/d' passwd
# Delete users who can't log in. Never execute on my machine. That's what my ftp users are doing.

sed -i '/^Yao Mao Mao/,/$2019/d' passwd
# Delete lines beginning with Yao Maomao and ending in 2019

Now let's summarize the commonly used parameters and built-in command characters for sed:

No parameters, only show the modified content in the terminal, do not modify the real file content, generally can be used with the pipeline "|" as the input source.

Parameter - i, must be added in order to really modify the file.

The parameter - n, commonly shared with the built-in command character p, displays the modified line.

Built-in command characters i, a, insert, append.

Built-in command characters s, d, replace, delete.

$stands for the end of the document, ^ stands for the beginning of the document.

As one of the three shell swordsmen (the other two are grep and awk), sed also has powerful regular expression functions, but I list some of the most commonly used functions in general operation and maintenance. If you are interested in sed, you can explore it by yourself if you want to do further research.

2.3 Document Search and Statistics

2.3.1 File Size Statistics and Sorting: du, sort du Common Commands
du -sh
# Statistical total size of current folder content

du -sh [Folder 1] [Document 1] 
# Statistics of folder or file sizes in the current directory

du -sh /usr/local
# Display the specified directory size

du -a
# Display the space occupied by all files in the current directory (including hidden files)

du -s
# Display the total size of the current directory

du -h
# Display the size of all files and directories in the current directory (including subdirectories), - h is converted to human readable results such as K, M, G, etc.

du -h *
# Statistics of the size of non-hidden files and directories in the current directory 

du -h --max-depth=1 [Catalog]
# Display only the size of the first level directory under the specified directory

du -h --max-depth=2 [Catalog]
# Display only the size of the first and second level directories of the specified directory

The picture shows:

du -sh

Statistical total size of current folder content

du -sh

Statistics of folder or file sizes in the current directory

du -sh /usr/local

Display the specified directory size

du -s

Display the total size of the current directory

du -h

- h is converted to human readable results such as K, M, G, etc.

du -a

Display the space occupied by all files in the current directory (including hidden files)

du -h --max-depth=1 /home/yao

Display only the size of the first level directory under the specified directory

du -h --max-depth=2 /home/yao

Display only the size of the first and second level directories of the specified directory

Summary of du common parameters:

- a or - all shows the size of individual files in the directory.
- b or - bytes display directory or file size in byte.
- c or -- total displays not only the size of individual directories or files, but also the sum of all directories or files.
- k or -- kilobytes are output in KB (1024 bytes).
- m or -- megabytes are output in MB.
- s or -- summarize shows only the total, listing only the final total.
- h or -- human-readable improves the readability of information in terms of K, M and G.

In addition, there are some parameters for reference, generally used to distinguish between hard and soft links to apply:

- x or -- one-file-xystep is based on the file system at the beginning of processing, and is skipped in case of other different file system directories.
- The source file size of the symbolic link specified in the L < symbolic link > or -- dereference < symbolic link > display options.
- S or -- separate-dirs show the size of individual directories, without the size of their subdirectories.
- X < File > or -- exclude-from= < File > specifies a directory or file in < File >.
- exclude=<directory or file> skips the specified directory or file.
- D or -- dereference-args displays the size of the source file for the specified symbolic link.
- H or - si has the same parameters as - h, but K, M and G are converted into 1000 units.
- l or -- count-links recalculates the files linked to the hardware. File Sorting: Common commands du + sort + head
du -a /home/yao | sort -n -r
#  Sort by file size in reverse order (with hidden files)

du -h /home/yao | sort -n -r | head -n 10
# Non-hidden files, the first 10 filters, the readable way to show the size of the file; 
# Sort-n-r can also write sort-rn.
# - n: Sort by the size of the values;
# - r: In reverse order;

du -h --max-depth=1 /home/yao | sort -n -r | head -n 10
# Specify the first layer of the directory, the first 10 filters, and display the file size in a readable way

du -h --max-depth=1 /home/yao | sort -rn -o 'sort.txt' | head -n 10
# Use the sort-o parameter to store the sorted results in the specified file

In addition, sort has other parameters, such as sorting by file name rather than size.

# The basic parameters of sort are as follows

- n: Sort by the size of the values;
- r: In reverse order;
- O < Output File >: Put the sorted results into the established file;

- b: Ignore the space characters that start at the front of each line;
- c: Check whether the files have been sorted in order;
- f: When sorting, lower-case letters are treated as upper-case letters.
- m: Merge several sort number files;

# The following parameters are mutually exclusive with the - n sort
 - i: When sorting, other characters are ignored except ASCII characters between 040 and 176.
-d: sorting, processing English letters, numbers and space characters, ignoring other characters;
- M: Sort the first three letters according to the abbreviations of the month.
2.3.2 Search for Documents I'm the best: find find examples of common commands
find / -name 'wfy.txt'
# Find the file wfy.txt from the root directory

find . -name '*fy.txt'
# Under the current directory, find the file with the suffix fy.txt
# "." denotes the current directory and "*" denotes any length character

find / -type f -size +500M
# Starting from the root directory, files over 500M
# / The root directory
# ...: Current catalogue
# - type f: f is a common file type, f is a directory file instead of d, l is a symbolic link file, - type has other parameters, not listed here.
# - size +500M: 500 MB or more 
# Usually there is not enough disk space. This command is used when deleting junk files.

find . -type f -size +1k
# Look for files that exceed 1k in the current folder. Note that k is lowercase.

find . -type f -mtime -30
# Find files that have been modified within 30 days in the current directory
# - mtime: Represents modification time, the most commonly used parameter is - atime, - ctime
# - atime: Represents the visit time, even if you have checked it.
# - ctime: File state change time
# - 30: Represents less than 30 days, 30 is n, the number fills in by oneself
# + 30:30 days ago
# 30:30 Days from now

find /var/log/ -mtime +30 -name '*.log'
# Find the log file in the specified directory / var/log / 30 days ago

find /etc ! -type f  
# Find files that are not ordinary files in the / etc directory
# "!": exclamation mark, take the opposite

find /etc ! -type l -mtime -30
# Find files that are not symbolically linked in the / etc directory and have been modified within 30 days
find /etc -maxdepth 1 ! -type l -mtime -30
# Find files that are not symbolically linked files in the first directory of / etc and have been modified within 30 days
# - maxdepth: As you've learned before, specify the directory hierarchy, - maxdepth 1 represents layer 1, and - maxdepth 2 represents extension to layer 2

- maxdepth may be a little hard to understand, so I cut a sample diagram. Use find combination command: statistics and deletion

The basic common find commands have been finished, and then a combination command may be commonly used in operation and maintenance, using find to delete files or logs N days ago.

First use wc-l to count the number of log s, and then delete it.

find / -name '*.log' -mtime +300 | wc -l
# Search the log files 300 days ago from the root directory and count the number
# "|": Pipeline character, which uses the data found earlier as input source for subsequent commands

The first way to delete: - exec

find / -name '*.log' -mtime +300 -exec rm {} \;
# Find the log file 30 days ago and delete it with - exec and rm
# Use the above command to review it again
find / -name '*.log' -mtime +300 | wc -l 

The second way to delete: - ok

find / -name '*.log' -mtime +200 -ok rm {} \;
# - ok: Inquiry deletion, y deletion, n deletion, return default deletion

The third way to delete: xargs

Execute the view results in turn

find / -name '*.log' -mtime +100 | wc -l

find / -name '*.log' -mtime +100 | xargs rm -f
# xargs: Command Pass Parameter Filter, used with Pipeline "|", to pass the previous command to the later command for use

find / -name '*.log' -mtime +100 | wc -l

Combination of find and xargs

Check the log file 50 days ago for details

find / -name '*.log' -mtime +50 | xargs ls -l
# Use xargs + ls-l command to view the detailed attributes of files

Remove files 50 days ago

mkdir /logback
# Create the / logback folder in the root directory

find / -name '*.log' -mtime +50 | xargs -i mv {} /logback
# Move all log files 50 days ago to the / logback folder
# Xargs-i + {}, execute the mv command with all the files found previously as parameters

ls -l /logback
# View all file details under / logback

The difference between xargs and exec under find

Difference one:

- exec is to pass the name of the result file to the following command to execute one by one. Most of the files will lead to inefficiency.

xargs, is a one-time transfer, high efficiency, and can use-n parameter to control the number of files transferred.

The difference is two:

- exec, special characters such as spaces in file names are also processed as usual.

Xargs, processing special file names (such as file names with spaces) requires special processing (find. - name "* edu" - pringt0 | xargs - 0ls - l)

Verify difference 1. Examples are as follows:

 find /logback -name '*.log'  -exec echo yaomaomao {} \;

find /logback -name '*.log'  | xargs echo yaomaomao 

You can see that using - exec to get a file output once at a time, xargs only outputs one line.

xargs can also use the - n parameter to control the number of files per output

find /logback -name '*.log'  | xargs -n5 echo yaomaomao 

As you can see, each line outputs five parameters (filename), and the insufficient line outputs the rest.

Verify the difference 2. Examples are as follows:

touch yaomaomao.txt;touch "yaomaomao centOS 7";ll yaomaomao*
# Tip: Use a semicolon to execute multiple commands at once
# Note: Use quotation marks when viewing and creating files with spaces

find . -name "yaomaomao*" -exec ls -lh {} \;
# Find out normally

find . -name  "yaomaomao*" | xargs ls -lh
# You can see that the file or directory could not be found using this command.

find . -name  "yaomaomao*" -print0 | xargs -0  ls -lh
# Normal lookup

In fact, find has many powerful functions, as you can see from the two pictures.

This book is my first recommendation of Core System Command Actual Warfare.

2.3.3 shell three swordsmen two: grep, character search has a hand grep Common Command Example:
grep -n 'No need' wfy.txt
# Find lines containing "no" characters in the wfy.txt file
# - n Displays Line Number
# - i Case-insensitive
# - v reverse filtration
# - c Statistical Matching Row

grep -c 'No need' wfy.txt
# Statistics of rows containing "no" character lines

grep -v 'No need' wfy.txt
# Find lines that do not contain "no" characters grep looks up multiple files at the same time
# Prepare the data first

cp wfy.txt wfy2.txt
# Copy a document

sed -i '1i I duplicate it. wfy2' wfy2.txt
# Use sed to precede the first line with a line heading to distinguish

cat wfy2.txt
# Look at the file you just copied

grep -n 'No need' wfy.txt wfy2.txt
# Query the contents of files containing "no" characters in multiple files and display line numbers
# Keep up with multiple parameters directly at the end

grep -n 'No need' *
# Query all files in the current directory that contain "no" files and display the corresponding line number grep recursive lookup
# Let's prepare the data first.

mkdir dirwfy ; cp wfy.txt dirwfy/wfy3.txt;sed -i '1i I am wfy3,Pay attention to' dirwfy/wfy3.txt;cat dirwfy/wfy3.txt
# Create the directory dirwfy, create the wfy3.txt file under the dirwfy directory, and modify the title

# Use grep-n above to see the effect
grep -n 'No need' *
# Documents under dirwfy could not be found

grep -rn 'No need' *
# As shown in the figure, you can find files under dirwfy grep finds n lines before and after corresponding characters
grep -A10 'Yao Mao Mao' wfy.txt
# Look at the 10-line data after the "Yao Mao Mao" character line
# -A : after

grep -B5 '5 you' wfy.txt
# Look at the first five lines of the "5 You" character
# -B: before

grep -A1 -B1 '7 you' wfy.txt
# Look at the data of each line before and after the "7 You" character grep combination command
history|grep rm
# Find which deletion commands were executed in the history command

rpm -qa |grep yum
# Query linux if this rpm package has been installed

ps -ef|grep java
# This command is the most commonly used command in general operation and maintenance. It queries whether the program has been run in the linux process.

pgrep -java
# Find a java process, the same function as above, but only show the process number

pgrep -l java
# Find a java process, the same function as above, but show the process number and process name

kill –9 'pgrep java'
# Batch shutdown of java processes
# Pgrep: Find a running program; pgrep is an extension of grep, as well as egrep and fgrep, with little understanding.  
# egrep: Extended regular expressions
# fgrep: Uncertainty of regular expressions

ps -ef |grep $ORACLE_SID|grep -v grep|awk '{print $2}' | xargs kill -9
# Get all oracle processes and close them
2.3.4 wc

The most commonly used commands of wc are combination commands, such as:

ls | wc -l
# Statistics of how many files are in the current folder

ls *.txt | wc -l

find . -maxdepth 1 -name '*.txt' | wc -l
# Statistics the number of txt files in the current folder and the first level directory
# Both of the above commands are acceptable

wc basic command:

wc -l /etc/inittab 
# Statistical file content line number
# - l: Statistical rows
# - w: Number of words counted
# - m: Statistical Character Number
# - c: Statistical byte count
# - L: Length of the longest line to print

# Take a look at all of them.
wc -l /etc/inittab;wc -c /etc/inittab; wc -m /etc/inittab;wc -w /etc/inittab; wc -L /etc/inittab

wc /etc/inittab
# The default output line number, word number, byte number without parameter
# The equivalent parameter is - lwc

# How is the number of bytes the same as the number of characters? Because it's all English, let's go inside and read it.

sed -i '1a #In'/etc/inittab

wc -lcmwL /etc/inittab
# Note: The output is not sorted by the parameters on the command line we typed out. It has a fixed order - > lwmcL
# according to lwmcl After ordering, you can see that the number of bytes is two bits more than the number of characters because of one.#The symbol is 1 bytes, an English character represents 2 bytes, and a Chinese character is 4 bytes.#So it adds 5 bytes, but only 2 characters.

Public numbers are registered late and have no comment function, so they are usually used to send long text.
Knowledge planet is equivalent to the circle of technological friends. If you have questions, you can ask and discuss them.

Welcome to my public number: Yao Maomao's blog

Welcome to my knowledge planet. It's free at present.
Knowledge Planet: Yao Maomao's Private Garden

Tags: Linux vim less Java

Posted on Wed, 09 Oct 2019 17:10:16 -0700 by the_damo2004