Linux pipe command line usage

what is a pipeline

What do pipes do in real life, such as water pipes, water pipes can be used to flow water from one side to the other side. What about pipes in Linux? The functions are similar. Linux pipes can output a command and flow to the other side. Another command, as input to another command, that's what Linux pipes.
In real life, water pipes are used to connect water. What about the input and output of connection commands in Linux? The pipe command character is used | .
The function of the pipe command character "|" is to use the standard output of the previous command as the standard input of the next command, the format is "command A | command B", for example

#在文本a.txt中寻找文本123所在段落。
cat a.txt | grep "123"

【Reminder】:

  1. The pipeline command only processes the correct output of the previous command, and does not process the wrong output;

  2. The command on the right side of the pipeline command must be able to receive the standard input stream command;

The pipe command and input and output redirection are actually a bit similar, because they both change the flow of data, but the target is different. Redirection >> means to output the output of a command to a file, and the pipeline is to put this The output of a command, as input to the next command.

If the pipeline command is used well, it can help us do many things, such as:
Example 1: Generate an 8-bit random password

tr -dc A-Za-z0-9_ </dev/urandom | head -c 8 | xargs

Example 2: View all user names in the system and sort them alphabetically

awk -F: '{print $1}' /etc/passwd | sort

Example 3: List the top 5 commands used by the current user (the number of columns in print depends on the actual situation)

history | awk '{print $2}' | sort | uniq -u | sort -rn | head -5

Example 4: View the login shells of users in the system /bin/bash

cat /etc/passwd | grep "/bin/bash" | cut -d: -f1,6   

#cut -d: -f1,6 表示以:为分隔符显示第1和第6列的内容-d指定分隔符,-f指定列

Example 5: View the number of subdirectories in the current directory

ls -l | cut -c 1 | grep "d" | wc -l

#ls -l  长格式列出当前目录的所有内容,每行的第一个字符表示文件的类

#cut -c 1 截取每行的第一个字符

#grep "d" 获取文件类型是目录的行

#wc -l  统计grep命令输出的行数,即子目录个数

Example 6: Merge the contents of two files

cat 1.txt | paste -d: 2.txt -

#paste -d: 2.txt - 表示以:为分割符合并两个文件,合并时2.txt文件的内容在前 -代表1.txt文件

Guess you like

Origin blog.csdn.net/qq_45171957/article/details/123698265