Skip to content

Instantly share code, notes, and snippets.

@ibreathebsb
Last active September 5, 2018 13:00
Show Gist options
  • Save ibreathebsb/de3e7260b77ccb0b18f8098529f11964 to your computer and use it in GitHub Desktop.
Save ibreathebsb/de3e7260b77ccb0b18f8098529f11964 to your computer and use it in GitHub Desktop.

pipe |

管线对stderr无效,管线后的命令能够读取stdout

cut

cut用于处理单行数据,如果输入有多行会对每行进行同样的处理,适用于格式比较工整的输入

cut -d'divider' -fbc LIST: d: divider, c: character, b: byte, f: filed

  1. 常用: echo $PATH | cut -d':' -f 2,3: 将$PATH用':'分隔,然后取其中的第二个和第三个
  2. echo $PATH | cut [-b|-c] 1,2: 获取$PATH的第1,2个字节/字符

grep

用于对多行内容的查找,如果某行符合条件就将该行输出

grep

# -c只输出符合条件的总行数而不是具体内容
ls -al | grep -c .bash 
# -i 忽略大小写
# -n 顺便输出行号
# -v 反选,即列出不符合条件的
# -a 将二进制文件当做文本处理
# -e regexp正则匹配

sort

-f:忽略大小写

-b: 忽略最开头的空格

-n: 使用数字排序,默认使用字符

-r: 反向排序

-u: unique相同的内容只展示一行

-t: 一行内的分割符号

-k:依每行内的第几个filed排序

# 对/etc/passwd按照uid升序排序

isaac@hp:~$ cat /etc/passwd | sort -n -t ':' -k 3
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync

uniq

去除重复

uniq -i: 忽略大小写

uniq -c: 统计次数

~ last | cut -d' ' -f 1 | sort | uniq -c
   1
   1 _mbsetupuser
 218 isaac
  21 reboot
   5 root
  18 shutdown
   1 wtmp
   3 xmly

wc

word count, line count , byte count 文本统计

-c: 输出字节总数

-l: 输出总行数

-m: 字符总数统计

-w: 单词统计

tee

双向倒流工具

ls -al | grep '.bash' | tee -a somefile | sort

经过tee处理的stin还会继续输出到stdout

tee -a FILE: a: append将内容append到文件中

@ibreathebsb
Copy link
Author

xargs

将stdoutput变成参数传递给后续的命令

# 示例
isaac@hp:~/Playground$ whoami | xargs touch
isaac@hp:~/Playground$ ls
isaac  new

# -0 将特殊字符以普通字符传递给后续命令
# -e 指定eof
# -p 执行命令时提示用户
# -n 指定传给后续命令的参数的个数


# 每次传递一个参数
isaac@hp:~/Playground$ ls | xargs -p -n 1 rm
rm isaac ?...y
rm new ?...y

# 每次传递两个参数
isaac@hp:~/Playground$ echo 1 2 | xargs -p -n 2 touch
touch 1 2 ?...y

# 自定义eof,注意-e后面没空格

isaac@hp:~/Playground$ echo 1 2 X 3 4 | xargs -p -e'X' touch
touch 1 2 ?...y

# 一个无聊的示例
# ls本身不能接受stdout,借助xargs便可以实现

isaac@hp:~/Playground$ ls | xargs ls -l 
-rw-r--r-- 1 isaac isaac 0 Sep  5 20:51 1
-rw-r--r-- 1 isaac isaac 0 Sep  5 20:51 2

@ibreathebsb
Copy link
Author

特殊的-

即可以用作stdin, 又可以用作stdout

# 把/home下的文件打包输出到stdout作为解包的输入
tar -cvf - /home |  tar -xvf -

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment