Article directory
Linux file content viewing and editing
1. View file content
cat usage
cat
Command is used to display the contents of the entire file. It outputs the contents of the file to the terminal window in one go.
For example, to display the contents of a file named file.txt
, run the following command:
cat file.txt
Tips: If the file content is too long to be displayed completely on the terminal at one time, you can use the less
or more
command for paging display.
Detailed explanation of cat
Concatenate multiple files and print to standard output.
overview
cat [OPTION]… [FILE]…
The main purpose
- Display the contents of the file, or read standard input if there is no file or the file is -.
- Concatenate the contents of multiple files and print them to standard output.
- Display invisible characters (control characters, newlines, tabs, etc.) in the file contents.
parameter
FILE (optional): The file to be processed can be one or more.
Options
Long options are equivalent to short options
- -A, --show-all is equivalent to the "-vET" combination option.
- -b, --number-nonblank Only number non-blank lines, starting from 1, overriding the "-n" option.
- -e is equivalent to the "-vE" combination option.
- -E, --show-ends Display '$' characters at the end of each line.
- -n, --number Number all lines, starting from 1.
- -s, --squeeze-blank Squeeze consecutive blank lines into one line.
- -t is equivalent to the "-vT" combination option.
- -T, --show-tabs Use "^I" to represent TAB (tab character).
- -u POSIX compatibility option, meaningless.
- -v, --show-nonprinting Use "^" and "M-" symbols to display control characters, except LFD (line feed, that is, newline character '\n') and TAB (tab character).
- –help Display help information and exit.
- –version Display version information and exit.
return value
The return status is success unless illegal options or illegal parameters are given.
example
# 合并显示多个文件
cat ./1.log ./2.log ./3.log
# 显示文件中的非打印字符、tab、换行符
cat -A test.log
# 压缩文件的空行
cat -s test.log
# 显示文件并在所有行开头附加行号
cat -n test.log
# 显示文件并在所有非空行开头附加行号
cat -b test.log
# 将标准输入的内容和文件内容一并显示
echo '######' |cat - test.log
Notice
- This command is in the GNU coreutils package. For related help information, please see
man -s 1 cat
orinfo coreutils 'cat invocation'
. - When using the cat command to view a large file, the text flashes across the screen quickly (scrolls), and the user often cannot see the displayed content clearly. In order to control the scrolling, you can press Ctrl+s to stop scrolling; press Ctrl+q key to resume scrolling; press Ctrl+c (interrupt) key to terminate the execution of the command and return to the Shell prompt state.
- It is recommended that you use less and more commands or text editors such as emacs and vi when viewing larger files.
less
less
The command can view file contents by page and provides some convenient browsing operations.
To view the contents of a file using less
, just enter the following command:
less file.txt
The first page of the file contents is displayed. You can use the arrow keys to scroll up/down, or press the space bar to page down.
Tips: To exit the less
command, press the q
key.
less detailed explanation
Split screen to flip up and down pages to browse file contents
Additional information
less
The command is very similar to the more
command, which can be used to browse the contents of text files. The difference is that the less
command allows the user to move forward or backward. browse the file backward, while the more
command can only browse forward. When using the less
command to display a file, use the PageUp
key to page up and the PageDown
key to page down. To exit the less
program, press the Q
key.
grammar
less [选项] [参数]
Options
-e
: Automatically exit after the file content is displayed;-f
: Force display of files;-g
: Do not highlight all searched keywords, only display the currently displayed keywords to improve display speed;-l
: Ignore case differences when searching;-N
: Display the line number at the beginning of each line;-s
: Compress multiple consecutive blank lines into one line for display;-S
: Display longer content in a single line without wrapping;-x<数字>
: Display TAB characters as a specified number of space characters.
parameter
- File: Specify the file to display content in split screen.
Example
sudo less /var/log/shadowsocks.log
more
Similar to less
, the more
command can also be used to view file contents by page.
To view the contents of a file using more
, just enter the following command:
more file.txt
differs from less
in that more
only allows you to scroll forward one page and cannot scroll forward like less
Post scroll.
Tips: To exit the more
command, press the q
key.
more detailed explanation
more
The command is used to display the file contents in pages.
Additional information
more
The command is a text filter based on the vi
editor. It displays the contents of a text file in full-screen mode and supports vi
Keyword targeting operations in . more
has many built-in shortcut keys, such as:
H
: Get help information.Enter
: Scroll down one line.- Space: Scroll down one screen.
Q
:Exit the command.
This command displays one screen of text at a time, stops when the screen is full, and displays a prompt message at the bottom of the screen, giving the percentage of the file that has been displayed: "-More-(XX%)". You can answer the prompts in the following ways:
- Press
Space
key: Display the next screen of text. - Press
Enter
key: Only the next line of text will be displayed. - Press the slash character
|
: Then enter a pattern to find the next matching pattern in the text. - Press
H
key: Display the help screen with relevant help information. - Press
B
key: Display the previous screen content. - 按
Q
Key: Exitmore
Command.
grammar
more [选项] [文件]
Options
-<数字>
: Specify the number of lines displayed on each screen.-d
: Display prompt information.-c
: No scrolling operation is performed, and the screen is refreshed every time.-s
: Condens multiple blank lines into one line for display.-u
: Underlines are prohibited.+<数字>
: Display starts from the line with the specified number.
parameter
文件
: The file whose content is to be displayed in pages.
Example
Display file
the contents of the file, but clear the screen before displaying, and display the completion percentage at the bottom of the screen.
more -dc file
Display file
The contents of the file are displayed every 10 lines, and the screen is cleared before displaying.
more -c -10 file
2. File search and filtering
grip
grep
Command is used to search a file for a specified pattern. It matches the pattern you provide and outputs the matching lines.
Here's the basic syntax for using grep
:
grep pattern file.txt
Where, pattern
is the pattern you want to search for, and file.txt
is the file name you want to search for.
For example, to search for lines containing the word "hello" in a file named file.txt
, you would run the following command:
grep hello file.txt
grep
The command also provides many options for more flexible searching. You can view the complete help documentation through the man grep
command.
Detailed explanation of grep
grep
The command is used to search a file for a specified pattern and output matching lines.
grammar
grep [选项] 模式 [文件]
Options
-i
: Ignore case.-v
: Reverse matching, only output unmatched lines.-r
: Recursively search all files in the directory.-l
: Only output file names containing matching patterns.-c
: Output only the number of matching lines.-n
: Output matching lines and line numbers simultaneously.-H
: When searching for multiple files, display matching lines and file names.
parameter
模式
: The pattern to search for, which can be a normal string or a regular expression.文件
:Specify the files to search for.
Example
-
Search the file
example.txt
for lines containing the string "hello" and output the matching lines:grep "hello" example.txt
-
Search multiple files for lines matching the pattern "pattern" and display the matching lines and file names:
grep -H "pattern" file1.txt file2.txt
-
Recursively search for lines matching the pattern "keyword" in the directory
directory
and its subdirectories, and output the matching lines and line numbers:grep -r -n "keyword" directory
-
Search the file for lines that do not contain the pattern "exclude" and output the lines that do not match:
grep -v "exclude" example.txt
find
find
The command can be used to find files that meet the criteria under the specified path.
Here's the basic syntax for using find
:
find path -name filename
Among them, path
is the path to be searched, and filename
is the file name to be searched.
For example, to find a file named file.txt
in the current directory and its subdirectories, run the following command:
find . -name file.txt
find
The command also supports other conditions, such as searching by file type, size, etc. You can view the complete help documentation through the man find
command.
Detailed explanation of find
find
The command is used to find files or directories that meet the conditions in the specified directory.
grammar
find [路径] [表达式]
Options
-name
: Match according to file name.-type
: Match according to file type.-size
: Match according to file size.-mtime
: Match according to file modification time.-exec
: Execute a command on the search results.
parameter
路径
: The directory path to be searched.表达式
: An expression used to specify search conditions.
Example
-
Find a file named "example.txt" in the current directory and its subdirectories:
find . -name "example.txt"
-
Look for files in the
/var/log
directory whose file names end with ".log":find /var/log -name "*.log"
-
Find files of type Normal and larger than 1MB in the current directory and its subdirectories:
find . -type f -size +1M
-
Find files that have been modified in the last 7 days in the
/tmp
directory and output the results to theresult.txt
file:find /tmp -mtime -7 > result.txt
-
Find files whose file names end with ".txt" and pass the search results to the command following
-exec
for processing (such as deletion):find . -name "*.txt" -exec rm {} \;
awk
awk
It is a powerful text processing tool that can process and analyze files according to specified rules.
Here's the basic syntax for using awk
:
awk 'pattern { action }' file.txt
Among them, pattern
is the pattern to be matched, action
is the operation to be performed, and file.txt
is to be processed file name.
For example, to extract the first column of data in a file named file.txt
, you would run the following command:
awk '{ print $1 }' file.txt
awk
also supports more complex operations, such as conditional judgment, looping, etc. If you'd like to learn more about using awk
, please see the documentation or tutorial.
Detailed explanation of awk
awk
It is a command line tool for processing text files. It is used to analyze and manipulate text data. It supports various mathematical and string functions as well as conditional statements and loop statements.
grammar
awk [选项] '表达式' [文件]
Options
-F
: Specify the field delimiter of the input file.-v
: Define a variable and assign a value.-f
: Use script files to execute commands.
parameter
表达式
: A script containing theawk
command for processing input files.文件
: The input file to be processed.
Example
-
The first and third columns in the output file
/etc/passwd
:awk -F ":" '{print $1, $3}' /etc/passwd
-
Number of lines containing the keyword "error" in statistics file
/var/log/messages
:awk '/error/ {count++} END {print count}' /var/log/messages
-
Use variables and arithmetic operations to process data in file
/proc/meminfo
:awk -v total=0 '/MemTotal/ {total+=$2} /SwapTotal/ {total+=$2} END {print total / 1024 " MB"}' /proc/meminfo
-
Use script file
script.awk
to process file/var/log/auth.log
:awk -f script.awk /var/log/auth.log
3. File editing
nano
nano
It is a simple and easy-to-use text editor suitable for novice users.
To edit a file using nano
, just enter the following command:
nano file.txt
This will open in a terminal window file.txt
where you can edit and save the file.
Tips: In nano
, some commonly used shortcut keys for operations will be displayed at the bottom, such as saving files, exiting editing, etc.
Detailed explanation of nano
nano
It is a simple and easy-to-use text editor, used in the terminal, supporting basic text editing operations and shortcut keys.
grammar
nano [选项] [文件]
Options
-B
: Enable the backup function, a backup file will be created when saving a file.-C
: Enable automatic line wrapping.-E
: Disable visual scroll bars.-G
: Disable mouse support.-i
: Automatically indent new lines.-m
: Enable mouse support.-O
: Disable automatic line wrapping when writing files.-R
: Open the file in read-only mode.-S
: Disable scroll synchronization function.-T
: Specifies syntax highlighting mode (such as-T python
).
parameter
文件
: The file path to be edited.
Example
-
Use
nano
Editexample.txt
:nano example.txt
-
Enable backup and edit files
example.txt
:nano -B example.txt
-
Use mouse support and edit files
example.txt
:nano -m example.txt
-
Open file in read-only mode
example.txt
:nano -R example.txt
The above is a brief introduction to the nano
command. You can use different options and parameters to perform text editing operations according to your needs. In the nano
editor, you can use shortcut keys to perform common operations such as cut, copy, paste, search and replace. Specific shortcut key information can be obtained through Ctrl+G
or < /span>F1
key to view.
vi/vim
vi
or vim
is a powerful text editor widely used on Linux systems.
To open a file using vi
, just enter the following command:
vi file.txt
At this time, you will enter the editing mode of vi
, and you can perform operations such as inserting, deleting, and replacing.
Tip: To save changes and exitvi
, press the Esc
key, then enter :wq
and press Enter key.
Detailed explanation of vi/vim
vi
and vim
is a powerful text editor that is widely used for text editing in terminal environments. vim
is an enhanced version of vi
, providing more features and improvements.
grammar
vi [选项] [文件]
vim [选项] [文件]
Options
-b
: Open the file in binary mode.-c <命令>
: Execute the specifiedEx
command.-C
: Enable compatibility mode.-E
: StartEx
mode (no interface is displayed).-g
: Enable graphical interface mode.-i <配置文件>
: Use the specified configuration file.-m
: Enable modification mode.-n
: Disable automatic word wrapping.-R
: Open the file in read-only mode.-s
: Quiet mode, suppress warning messages.-u <vimrc>
: Use the specifiedvimrc
profile.-w <脚本文件>
: Save the recorded macro to the specified script file.
parameter
文件
: The file path to be edited.
Example
-
Use
vi
Editexample.txt
:vi example.txt
-
Use
vim
Editexample.txt
:vim example.txt
-
Open file in read-only mode
example.txt
:vim -R example.txt
-
Execute the
vim
command and then execute the specifiedEx
command, for example, delete all lines:vim -c ":%d" example.txt
vi
The and vim
editors have many powerful editing and operation functions, including insertion, deletion, copy, paste, search and replace, split window, etc. You can use shortcut keys and commands to complete various editing tasks. Detailed operation and command information can be obtained through vim
's help document (:help
).
Summarize
In Linux, we often need to view and edit the contents of files. Below we summarize some commonly used commands.
-
View file contents:
cat
The :cat
command is a simple and commonly used file viewing tool. It can display the contents of the entire file or connect multiple files together for display.less
The :less
command is a more powerful and flexible file viewing tool. It can browse files by page and supports forward and backward searches, scrolling up and down, and other functions.more
: Themore
command is similar toless
and is also a tool used to display file contents in pages.
-
File search and filtering:
grep
The :grep
command is a tool used to search a file for a specified pattern. It can match and filter content based on regular expressions and output the matched lines.find
: Thefind
command is used to search for files and directories in the specified directory. Files can be searched based on different criteria, such as filtering by name, size, time, etc.awk
:awk
is a powerful text processing tool that scans line by line in files and performs various operations. It can extract, transform and process text data according to customized rules.
-
File editing:
nano
:nano
is a simple and easy-to-use text editor for use in the terminal. It supports basic text editing operations and shortcut keys, making it suitable for beginners.vi/vim
:vi
andvim
are powerful text editors that are widely used for editing in terminal environments. They provide rich editing and operation functions and are suitable for experienced users.
The above is a summary of some common commands for viewing and editing Linux file contents. According to different needs and usage scenarios, we can flexibly choose appropriate commands to process files. Remember, mastering these commands will make you more comfortable on your Linux system!