Linux常用命令

    博客分类: 笔记 阅读次数:

Linux常用命令

Linux常用命令

快捷键

进程相关

ps

process status的简称。常用参数:

-e:显示所有进程
-f:显示uid、ppid等项

top

动态显示进程信息,类似与Windows的任务管理器

进入top命令后,热键r可以重置一个进程的优先级,热键k可以终止一个进程。

pstree

树状图显示进程信息

pgrep

通过进程名查找进程。

nice

调整进程优先级

$ nice -n 5 top

kill

发送信号到指定进程以终止该进程

$ kill -9 pid

kill默认是发送编号为15的SIGTERM信号,岂会在进程终止前安置好正在进行的工作。若无法杀死进程,可以发送编号为9的SIGKILL信号强制关闭进程,进程将立即终止,正在进行的修改将不会被保存。

文本过滤

文本过滤指的是这样一个过程:获得文本的输入流,并在将文本发送给输出流之前对文本执行一些转换。实现过滤的最常见方法是构建一个命令管道,其中来自一个命令的输出被传输重定向 以用作下一个命令的输入。

只不过是一个可以使用库功能读取或写入的字节序列,库功能向应用程序隐藏了底层设备的细节。通过使用流,相同的程序可以使用独立于设备的方式从终端、文件或网络 socket 中读取,或向其中写入。现代编程环境和 shell 使用三种标准的 I/O 流:

  1. stdout标准输出流,它显示来自命令的输出。它的文件描述符为 1。
  2. stderr标准错误流,它显示来自命令的错误输出。它的文件描述符为 2。
  3. stdin标准输入流,它为命令提供输入。它的文件描述符为 0。

一种常见的执行任务的方式就是构建一个长的命令管道,每个命令只具备有限的功能。有时会使用一个连字符 (-) 来代替文件名作为命令的参数,这意味着输入应当来自 stdin。

在本节后面的内容中,我们将使用一些小型文件,因此让我们创建一个名为 lpi103-2 的目录并通过 cd 进入到该目录。随后使用 > 将 echo 命令的输出重定向到名为 text1 的文件。

[ian@echidna ~]$ mkdir lpi103-2
[ian@echidna ~]$ cd lpi103-2
[ian@echidna lpi103-2]$ echo -e "1 apple\n2 pear\n3 banana" > text1

cat和split

使用 catconcatenate 的简写) 显示文件内容

[ian@echidna lpi103-2]$ cat text1
1 apple
2 pear
3 banana

如果没有指定文件名(或者如果指定 - 作为文件名)的话,cat 命令将从 stdin 获取输入。让我们结合使用输出重定向来创建另一个文本文件。

[ian@echidna lpi103-2]$ cat >text2 
9       plum
3       banana
10      apple

cat 将一直从 stdin 中读取文件,直到读完全部文件。使用Ctrl-d组合键来表示已到文件末尾。使用相同的组合键来退出 bash shell。

另一个小型过滤器的例子就是 tac 命令。这个命令的名称正好与 cat 相反,并且其功能也与 cat 的功能相反,因为这个文件是按行逆序显示的。

[ian@echidna lpi103-2]$ tac text1
3 banana
2 pear
1 apple

可以使用 cat 将多个文件链接在一起一并显示。

[ian@echidna lpi103-2]$ cat text*
1 apple
2 pear
3 banana
9       plum
3       banana
10      apple

有时会遇到特别大的文件,需要将其拆分为比较小的文件。split 命令将实现这一目的。

split [OPTION] [INPUT [PREFIX]]

把 INPUT 按 固定大小 的 文件片 PREFIXaa, PREFIXab, … 输出; 缺省的 PREFIX 是’x’。如果没有指定 INPUT, 或 INPUT 是 -, 就从 标准输入 读取数据。可选OPTION如下:

-b, --bytes=SIZE	输出文件大小定为 SIZE 字节
-C, --line-bytes=SIZE	输出文件大小定为最多 SIZE 字节的行
-l, --lines=NUMBER	输出文件大小定为 NUMBER 行
lfxyl@HP:~$ split -b 17 text2 y
lfxyl@HP:~$ cat yaa
9       plum
3   lfxyl@HP:~$ cat yab
    banana
10    lfxyl@HP:~$ cat yac
  apple
lfxyl@HP:~$ cat y*
9       plum
3       banana
10      apple

注意,名为 yaa 的分解文件并未使用换行符表示结束,因此当使用 cat 显示提示之后,会发现提示出现了偏移。

wc、head 和 tail

wc 命令将显示文件中所含的行、单词、字节的数量。

[ian@echidna lpi103-2]$ ls -l text*
-rw-rw-r-- 1 ian ian 24 2009-08-11 14:02 text1
-rw-rw-r-- 1 ian ian 25 2009-08-11 14:27 text2
[ian@echidna lpi103-2]$ wc text*
3  6 24 text1
3  6 25 text2
6 12 49 total

headtail将显示文件或流的前 10(或后 10)行。-n 参数可指定现实行数。下面的代码使用 dmesg 命令显示启动信息,并结合使用 wctailhead 执行下面的操作:发现共有 791 行消息,显示这些消息中的最后 10 条消息,最后显示倒数 15 条消息中的前 6 条消息。某些行在输出中被截短(使用 … 表示)。

lfxyl@HP:~$ dmesg | wc
   1434   13206  111080
lfxyl@HP:~$ dmesg | tail # 显示最后十行
[19195.591993] pcieport 0000:00:1c.5:   device [8086:a115] error status/mask=00000001/00002000
[19195.591998] pcieport 0000:00:1c.5:    [ 0] RxErr                 
[19403.286923] pcieport 0000:00:1c.5: AER: Corrected error received: 0000:00:1c.5
[19403.286937] pcieport 0000:00:1c.5: PCIe Bus Error: severity=Corrected, type=Data Link Layer, (Receiver ID)
[19403.286945] pcieport 0000:00:1c.5:   device [8086:a115] error status/mask=00000040/00002000
[19403.286950] pcieport 0000:00:1c.5:    [ 6] BadTLP                
[20109.308723] pcieport 0000:00:1c.5: AER: Corrected error received: 0000:00:1c.5
[20109.308732] pcieport 0000:00:1c.5: PCIe Bus Error: severity=Corrected, type=Physical Layer, (Receiver ID)
[20109.308734] pcieport 0000:00:1c.5:   device [8086:a115] error status/mask=00000001/00002000
[20109.308736] pcieport 0000:00:1c.5:    [ 0] RxErr                 
lfxyl@HP:~$ dmesg | tail -n 3  # 显示最后三行
[20109.308732] pcieport 0000:00:1c.5: PCIe Bus Error: severity=Corrected, type=Physical Layer, (Receiver ID)
[20109.308734] pcieport 0000:00:1c.5:   device [8086:a115] error status/mask=00000001/00002000
[20109.308736] pcieport 0000:00:1c.5:    [ 0] RxErr                 
lfxyl@HP:~$ dmesg | tail |head -n 3  # 最后十行的前三行
[19195.591993] pcieport 0000:00:1c.5:   device [8086:a115] error status/mask=00000001/00002000
[19195.591998] pcieport 0000:00:1c.5:    [ 0] RxErr                 
[19403.286923] pcieport 0000:00:1c.5: AER: Corrected error received: 0000:00:1c.5

==tail 的另一个常见用法就是使用 -f 选项跟踪(follow)文件,当文件增长时,输出后续添加的数据。在这种模式下,tail 将一直运行,直到您将其取消(使用 Ctrl-c),它将在行被写入文件时显示它们。==

tr

tr (traslate)命令用于转换或删除文件中的字符。tr [OPTION] SET1 [SET2]

-c, --complement:反选设定字符。符合 SET1 的部份不做处理,不符合的剩余部份才进行转换
-d, --delete:删除SET1中字符
-s, --squeeze-repeats:缩减连续重复的字符成指定的单个字符
-t, --truncate-set1:削减 SET1 指定范围,使之与 SET2 设定长度相等
lfxyl@HP:~$ echo "aaAA1bbBB2ccCC3" | tr 'ab' '123'
11AA122BB2ccCC3		# a被替换成1,b被替换成2
lfxyl@HP:~$ echo "aaAA1bbBB2ccCC3" | tr 'abc' '12'
11AA122BB222CC3		# a被替换成1,b被替换成2,c被替换成2
lfxyl@HP:~$ echo "aaAA1bbBB2ccCC3" | tr -d a-z 
AA1BB2CC3			# 删除小写字母

# 大小写转换
lfxyl@HP:~$ cat text1
1 apple
2 pear
3 banana
lfxyl@HP:~$ cat text1|tr a-z A-Z
1 APPLE
2 PEAR
3 BANANA

set1 和set2 的范围表示请看man手册

nl

nl 命令可以对行进行编号,这在输出文件时非常方便。也可以使用 cat 命令的 -n 选项对行进行编号。

lfxyl@HP:~$ nl text*
     1	1 apple
     2	2 pear
     3	3 banana
     4	9       plum
     5	3       banana
     6	10      apple

sort 和 uniq

sort对文本文件的行排序。默认将文本文件的第一列以ASCII 码的次序排列,并将结果输出到标准输出。

lfxyl@HP:~$ cat text2
9       plum
3       banana
10      apple
lfxyl@HP:~$ cat text2 |sort
10      apple
3       banana
9       plum
lfxyl@HP:~$ cat text2 |sort -g 	# 按照通常的数字值顺序作比较
3       banana
9       plum
10      apple

uniq 命令用于检查及删除文本文件中重复出现的行,一般与 sort 命令结合使用。

$ cat testfile      #原有内容  
test 30  
test 30  
test 30  
Hello 95  
Hello 95  
Hello 95  
Hello 95  
Linux 85  
Linux 85 
$ uniq -c testfile      # -c显示重复次数
3 test 30             
4 Hello 95            
2 Linux 85             

当重复的行并不相邻时,uniq 命令是不起作用的,此时需要与sort命令一起使用。

tee

tee 从标准输入读入并写往标准输出和文件。

lfxyl@HP:~$ echo "haha"|tee text1 text2
haha
lfxyl@HP:~$ cat text1
haha
lfxyl@HP:~$ cat text2
haha
lfxyl@HP:~$ 

-a参数:追加到给出的文件,而不是覆盖。

grep

简介

grep与sed、awk并称Linux中的三剑客,其全称是 Global search Regular Expression and Print out the line。

语法格式:

grep [options] [pattern [file]

常用参数:

-c 计算找到‘搜索字符串’的行数
-o 指数出匹配的内容
-i 不区分大小写
-n 显示匹配内容的行号
-r 当指定要查找的是目录而非文件时,必须使用这项参数,否则grep命令将回报信息并停止动作
-v 反向选择,即没有‘搜索字符串’内容的行
-l 列出文件内容符合指定的范本样式的文件名称
-E egrep,可以使用扩展正则表达式
-F fgrep, 不支持正则表达式
–color 高亮查找词

正则表达式种类繁多且复杂,POSIX 将正则表达式进行了标准化,并把实现方法分为了两大类:

两者的区别,更多的是元字符的区别。在基本正则表达式(BRE)中,只承认^、$、.、[、]、*这些是元字符,所有其他的字符都被识别为普通字符。而在扩展正则表达式(ERE)中,则在BRE的基础上增加了(、)、{、}、?、+、|等元字符。

示例

$ cat /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
(中间省略数十行)
apache:x:48:48:Apache:/var/www:/sbin/nologin
test:x:502:502::/home/test:/bin/bash
leo:x:503:503::/home/leo:/bin/bash
roc:x:504:504::/home/roc:/bin/bash
# 搜索包含leo字符串的行:
$ grep leo /etc/passwd
leo:x:503:503::/home/leo:/bin/bash
$ grep -v leo /etc/passwd
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
(中间省略数十行)
apache:x:48:48:Apache:/var/www:/sbin/nologin
test:x:502:502::/home/test:/bin/bash
roc:x:504:504::/home/roc:/bin/bash

# 使用选项 n
$ grep -n leo /etc/passwd
29:leo:x:503:503::/home/leo:/bin/bash
# 使用-c选项
$ grep -c leo /etc/passwd
1
$ grep -i "LEO" /etc/passwd
leo:x:503:503::/home/leo:/bin/bash

grep 命令可以一次搜索很多个文件,从大量的文件中找出含有特定字符的文件.

# 当前目录下有三个文件
$ ll
total 12
-rw-rw-r-- 1 roc roc 58 Mar 15 17:47 1.txt
-rw-rw-r-- 1 roc roc 59 Mar 15 17:51 2.txt
-rw-rw-r-- 1 roc roc 58 Mar 15 17:52 3.txt
# 1.txt文件的内容如下
$ cat 1.txt
this first file
this file contain some import infomation.
# 2.txt文件的内容如下
$ cat 2.txt
this second file
this file contain some import infomation. 
# 3.txt文件的内容如下
$ cat 3.txt
this third file
this file contain some import infomation.

找出内容中含有first单词的文件

$ grep -l "first" *.txt
1.txt
# 找出不含 first 单词的文件都有哪些
$ grep -L "first" *.txt
2.txt
3.txt

grep支持正则:

# 搜索/etc/passwd文件中开头是 leo 的行
$ grep '^leo' /etc/passwd 
leo:x:503:503::/home/leo:/bin/bash
# 使用<bin>来表示bin是一个词,避免匹配到sbin
$ grep '\<bin\>' /etc/passwd 
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
cloud-user:x:500:500::/home/cloud-user:/bin/bash
test:x:502:502::/home/test:/bin/bash
leo:x:503:503::/home/leo:/bin/bash
roc:x:504:504::/home/roc:/bin/bash

egrep 可以实现多条件查找

# 查找以root为首或以bash为尾的行
$ egrep '^root|bash$' passwd
root:x:0:0:root:/root:/bin/bash
cloud-user:x:500:500::/home/cloud-user:/bin/bash
test:x:502:502::/home/test:/bin/bash
leo:x:503:503::/home/leo:/bin/bash
roc:x:504:504::/home/roc:/bin/bash

假如搜索字符串中包含了不少特殊字符,而这些特殊字符恰好又是正则表达式预留的字符,就可以使用 fgrep 来避免烦琐的转义了,在 fgrep 的眼里,没有特殊字符,都是普通字符。

# 我们的roc.txt文件中有几个^和$
$ cat roc.txt
^this third file
^$this file contain some import infomation.
 
# grep会尝试去找开头为this的行, 但并未找到
$ grep '^this' roc.txt
 
# fgrep会老老实实地去找^this字符串, 它找到了
$ fgrep '^this' roc.txt
^this third file

awk

awk是处理文本文件的一个应用程序,它依次处理文件的每一行,并读取里面的每一个字段。对于日志、CSV 那样的每行格式相同的文本文件,awk可能是最方便的工具。

基本用法

awk的基本用法就是下面的形式。

$ awk 动作 文件名
# 示例
$ awk '{print $0}' demo.txt

上面示例中,demo.txtawk所要处理的文本文件。前面单引号内部有一个大括号,里面就是每一行的处理动作print $0。其中,print是打印命令,$0代表当前行,上面命令的执行结果,就是把每一行原样打印出来。

awk会根据空格和制表符,将每一行分成若干字段,依次用$1$2$3代表第一个字段、第二个字段、第三个字段等等。

$ echo 'this is a test' | awk '{print $3}'
a

下面,为了便于举例,我们把/etc/passwd文件保存成demo.txt

root:x:0:0:root:/root:/usr/bin/zsh
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

这个文件的字段分隔符是冒号(:),所以要用-F参数指定分隔符为冒号。然后,才能提取到它的第一个字段。

$ awk -F ':' '{ print $1 }' demo.txt
root
daemon
bin
sys
sync

变量

除了$ + 数字表示某个字段,awk还提供其他一些变量。

变量NF表示当前行有多少个字段,因此$NF就代表最后一个字段。

$ echo "this is a test" | awk '{print NF}'
4
$ echo 'this is a test' | awk '{print $NF}'
test

$(NF-1)代表倒数第二个字段。

$ awk -F ':' '{print $1, $(NF-1)}' demo.txt
root /root
daemon /usr/sbin
bin /bin
sys /dev
sync /bin

上面代码中,print命令里面的逗号,表示输出的时候,两个部分之间使用空格分隔。

变量NR表示当前处理的是第几行。

$ awk -F ':' '{print NR ") " $1}' demo.txt
1) root
2) daemon
3) bin
4) sys
5) sync

上面代码中,print命令里面,如果原样输出字符,要放在双引号里面。

awk的其他内置变量如下。

  • FILENAME:当前文件名
  • FS:字段分隔符,默认是空格和制表符。
  • RS:行分隔符,用于分割每一行,默认是换行符。
  • OFS:输出字段的分隔符,用于打印时分隔字段,默认为空格。
  • ORS:输出记录的分隔符,用于打印时分隔记录,默认为换行符。
  • OFMT:数字输出的格式,默认为%.6g

函数

awk还提供了一些内置函数,方便对原始数据的处理。

函数toupper()用于将字符转为大写。

$ awk -F ':' '{ print toupper($1) }' demo.txt
ROOT
DAEMON
BIN
SYS
SYNC

上面代码中,第一个字段输出时都变成了大写。

其他常用函数如下。

  • tolower():字符转为小写。
  • length():返回字符串长度。
  • substr():返回子字符串。
  • sin():正弦。
  • cos():余弦。
  • sqrt():平方根。
  • rand():随机数。

条件

awk允许指定输出条件,只输出符合条件的行。输出条件要写在动作的前面。

$ awk '条件 动作' 文件名

请看下面的例子。

$ awk -F ':' '/usr/ {print $1}' demo.txt
root
daemon
bin
sys

上面代码中,print命令前面是一个正则表达式,只输出包含usr的行。

下面的例子只输出奇数行,以及输出第三行以后的行。

# 输出奇数行
$ awk -F ':' 'NR % 2 == 1 {print $1}' demo.txt
root
bin
sync
# 输出第三行以后的行
$ awk -F ':' 'NR >3 {print $1}' demo.txt
sys
sync

下面的例子输出第一个字段等于指定值的行。

$ awk -F ':' '$1 == "root" {print $1}' demo.txt
root
$ awk -F ':' '$1 == "root" || $1 == "bin" {print $1}' demo.txt
root
bin

if 语句

awk提供了if结构,用于编写复杂的条件。

$ awk -F ':' '{if ($1 > "m") print $1}' demo.txt
root
sys
sync

上面代码输出第一个字段的第一个字符大于m的行。

if结构还可以指定else部分。

 $ awk -F ':' '{if ($1 > "m") print $1; else print "---"}' demo.txt
 root
 ---
 ---
 sys
 sync

sed

基本用法

sed英文全称是stream editor,遵循简单的工作流:读取(从输入中读取某一行),执行(在某一行上执行sed命令)和显示(把结果显示在输出中)。通常sed命令这样被调用:

sed [options] 'command' file

options是sed可以接受的参数,command是sed的命令集。command的一般形式是:

[addr]X[options] 

X是一个单个字母sed命令。[addr]是一个可选的行地址。如果[addr]是被指定的,那么命令X在匹配的行将被执行。[addr]可以使用一个单独的行号、正则表达式、或行的范围。附加[options]被用于一些sed命令。

常用参数:

-e script 、--expression=script:运行指定脚本,当只有一个命令时可以省略
-f script-file、--file=script-file:运行指定脚本文件
-n、--quiet、–-silent:只输出脚本处理过的内容
-i:直接修改原文件(默认不修改原文件,需要重定向)

命令说明:

a :新增, a 的后面可以接字串,而这些字串会在新的一行出现(目前的下一行)~
c :取代, c 的后面可以接字串,这些字串可以取代 n1,n2 之间的行!
d :删除,因为是删除啊,所以 d 后面通常不接任何咚咚;
i :插入, i 的后面可以接字串,而这些字串会在新的一行出现(目前的上一行);
p :打印,亦即将某个选择的数据印出。通常 p 会与参数 sed -n 一起运行~
s :取代,可以直接进行取代的工作哩!通常这个 s 的动作可以搭配正规表示法!例如 1,20s/old/new/g 就是啦!

删除

$ cat Sed.txt 
That is line 1,That is First line
That is line 2,the Second line,Empty line followed
 
That is line 4,That is Third line
That is line 5,That is Fifth line
# 将file的第一行删除后输出到屏幕
$ sed '1d' Sed.txt
this is line 2,the Second line,Empty line followed
 
this is line 4,this is Third line
this is line 5,this is Fifth line
# 由于sed默认不修改原文件,如果希望保存修改后的文件则需要用重定向
sed '1d' Sed.txt > saved_file
# 如果想直接修改文件,使用-i参数,不会有任何输出,而是直接修改了原文件,删除了第一行
# Sed-i '1d' file
 
#删除指定范围的行(第一行到最后行)
$ sed '1,$d' Sed.txt
$ sed '$d' Sed.txt
That is line 1,That is First line
That is line 2,the Second line,Empty line followed
 
That is line 4,That is Third line
#删除除指定范围以外的行(只保留第5行)
$ sed '5!d' Sed.txt
this is line 5,this is Fifth line
 
#删除所有包含Empty的行
$ sed '/Empty/d' Sed.txt
this is line 1,this is First line
 
this is line 4,this is Third line
this is line 5,this is Fifth line
 
#删除空行
$ sed '/^$/d' Sed.txt
this is line 1,this is First line
this is line 2,the Second line,Empty line followed
this is line 4,this is Third line
this is line 5,this is Fifth line

查找替换

# s命令用于替换文本,本例中使用LINE替换line,默认情况下只替换第一次匹配到的内容
$ sed 's/line/LINE/' Sed.txt
this is LINE 1,this is First line
this is LINE 2,the Second line,Empty line followed
 
this is LINE 4,this is Third line
this is LINE 5,this is Fifth line
 
# 要想每行最多匹配2个line,并改为LINE,可用如下方式,到第2行中有3个line,前两个被替换了
$ sed 's/line/LINE/2' Sed.txt
this is line 1,this is First LINE
this is line 2,the Second LINE,Empty line followed
 
this is line 4,this is Third LINE
this is line 5,this is Fifth LINE
# s命令利用g选项,可以完成所有匹配值的替换
$ sed 's/line/LINE/g' Sed.txt
this is LINE 1,this is First LINE
this is LINE 2,the Second LINE,Empty LINE followed
 
this is LINE 4,this is Third LINE
this is LINE 5,this is Fifth LINE
 
# 只替换开头的this为that
[root@localhost ~]# sed 's/^this/that/' Sed.txt
that is line 1,this is First line
that is line 2,the Second line,Empty line followed
 
that is line 4,this is Third line
that is line 5,this is Fifth line

# y命令可进行字符转换,其作用为将一系列字符逐个地变换为另外一系列字符
# 将数字1转换为A,2转换为B,4转换为C,5转换成D
$ sed 'y/1245/ABCD/' Sed.txt
this is line A,this is First line
this is line B,the Second line,Empty line followed

this is line C,this is Third line
this is line D,this is Fifth line

插入

使用i或a命令插入文本,其中i代表在匹配行之前插入,而a代表在匹配行之后插入

# 使用i在第二行前插入文本
$ sed '2 i Insert' Sed.txt
this is line 1,this is First line
Insert
this is line 2,the Second line,Empty line followed
 
this is line 4,this is Third line
this is line 5,this is Fifth line
 
# 使用a在第二行后插入文本
$ sed '2 a Insert' Sed.txt
this is line 1,this is First line
this is line 2,the Second line,Empty line followed
Insert
 
this is line 4,this is Third line
this is line 5,this is Fifth line
 
# 在匹配行的上一行插入问题
[root@localhost ~]# sed '/Second/i Insert' Sed.txt
this is line 1,this is First line
Insert
this is line 2,the Second line,Empty line followed
 
this is line 4,this is Third line

# 使用r命令可从其他文件中读取文本,并插入匹配行之后
# 将/etc/passwd中的内容读出放到Sed.txt空行之后
$ sed  '/^$/r /etc/passwd' Sed.txt
this is line 1,this is First line
this is line 2,the Second line,Empty line followed
 
root:x:0:0:root:/root:/bin/bash
......(略去内容)......
apache:x:48:48:Apache:/var/www:/sbin/nologin
this is line 4,this is Third line
this is line 5,this is Fifth li

打印和写文件

# 打印出文件中指定的行
$ sed-n '1p' Sed.txt  	# 一定要加-n参数,表示不打印没关系的行
this is line 1,this is First line

#使用p命令,则只打印实际处理过的行,简化了输出(使用-n参数)
[root@localhost ~]# sed-n 's/the/THE/p' Sed.txt
this is line 2,THE Second line,Empty line followed

# 使用w命令将结果保存到外部指定文件
$ sed-n '1,2 w output' Sed.txt
# 这里没有任何输出,因为输出被重定向到文件了
$ cat output
this is line 1,this is First line
this is line 2,the Second line,Empty line followed

xargs

标准输入与管道命令

Unix 命令都带有参数,有些命令可以接受”标准输入”(stdin)作为参数。

 $ cat /etc/passwd | grep root

上面的代码使用了管道命令(|)。管道命令的作用,是将左侧命令(cat /etc/passwd)的标准输出转换为标准输入,提供给右侧命令(grep root)作为参数。因为grep命令可以接受标准输入作为参数,所以上面的代码等同于下面的代码。

 $ grep root /etc/passwd

但是,大多数命令都不接受标准输入作为参数,只能直接在命令行输入参数,这导致无法用管道命令传递参数。举例来说,echo命令就不接受管道传参。

 $ echo "hello world" | echo

上面的代码不会有输出。因为管道右侧的echo不接受管道传来的标准输入作为参数。

xargs命令的作用,是将标准输入转为命令行参数。

 $ echo "hello world" | xargs echo
 hello world

上面的代码将管道左侧的标准输入,转为命令行参数hello world,传给第二个echo命令。

xargs命令的格式如下。

 $ xargs [-options] [command]

真正执行的命令,紧跟在xargs后面,接受xargs传来的参数。xargs的作用在于,大多数命令(比如rmmkdirls)与管道一起使用时,都需要xargs将标准输入转为命令行参数。

 $ echo "one two three" | xargs mkdir

上面的代码等同于mkdir one two three。如果不加xargs就会报错,提示mkdir缺少操作参数。

xargs 的单独使用

xargs后面的命令默认是echo

 $ xargs
 # 等同于
 $ xargs echo

大多数时候,xargs命令都是跟管道一起使用的。但是,它也可以单独使用。

输入xargs按下回车以后,命令行就会等待用户输入,作为标准输入。你可以输入任意内容,然后按下Ctrl d,表示输入结束,这时echo命令就会把前面的输入打印出来。

 $ xargs
 hello (Ctrl + d)
 hello

再看一个例子。

 $ xargs find -name
 "*.txt"
 ./foo.txt
 ./hello.txt

上面的例子输入xargs find -name以后,命令行会等待用户输入所要搜索的文件。用户输入"*.txt",表示搜索当前目录下的所有 TXT 文件,然后按下Ctrl d,表示输入结束。这时就相当执行find -name *.txt

-d 参数与分隔符

默认情况下,xargs将换行符和空格作为分隔符,把标准输入分解成一个个命令行参数。

$ echo "one two three" | xargs mkdir

上面代码中,mkdir会新建三个子目录,因为xargsone two three分解成三个命令行参数,执行mkdir one two three

-d参数可以更改分隔符。

$ echo -e "a\tb\tc" | xargs -d "\t" echo
a b c

上面的命令指定制表符\t作为分隔符,所以a\tb\tc就转换成了三个命令行参数。

-p 参数,-t 参数

使用xargs命令以后,由于存在转换参数过程,有时需要确认一下到底执行的是什么命令。

-p参数打印出要执行的命令,询问用户是否要执行。

$ echo 'one two three' | xargs -p touch
touch one two three ?...

上面的命令执行以后,会打印出要执行的命令,让用户确认。用户输入y以后(大小写皆可),才会真正执行。

-t参数则是打印出最终要执行的命令,然后直接执行,不需要用户确认。

$ echo 'one two three' | xargs -t rm
rm one two three

-0 参数与 find 命令

由于xargs默认将空格作为分隔符,所以不太适合处理文件名,因为文件名可能包含空格。

find命令有一个特别的参数-print0,指定输出的文件列表以null分隔。然后,xargs命令的-0参数表示用null当作分隔符。

$ find /path -type f -print0 | xargs -0 rm

上面命令删除/path路径下的所有文件。由于分隔符是null,所以处理包含空格的文件名,也不会报错。

还有一个原因,使得xargs特别适合find命令。有些命令(比如rm)一旦参数过多会报错”参数列表过长”,而无法执行,改用xargs就没有这个问题,因为它对每个参数执行一次命令。

$ find . -name "*.txt" | xargs grep "abc"

上面命令找出所有 TXT 文件以后,对每个文件搜索一次是否包含字符串abc

-L 参数

如果标准输入包含多行,-L参数指定多少行作为一个命令行参数。

$ xargs find -name
"*.txt"   
"*.md"
find: paths must precede expression: `*.md'

上面命令同时将"*.txt"*.md两行作为命令行参数,传给find命令导致报错。

使用-L参数,指定每行作为一个命令行参数,就不会报错。

$ xargs -L 1 find -name
"*.txt"
./foo.txt
./hello.txt
"*.md"
./README.md

上面命令指定了每一行(-L 1)作为命令行参数,分别运行一次命令(find -name)。

下面是另一个例子。

$ echo -e "a\nb\nc" | xargs -L 1 echo
a
b
c

上面代码指定每行运行一次echo命令,所以echo命令执行了三次,输出了三行。

-n 参数

-L参数虽然解决了多行的问题,但是有时用户会在同一行输入多项。

$ xargs find -name
"*.txt" "*.md"
find: paths must precede expression: `*.md'

上面的命令将同一行的两项作为命令行参数,导致报错。

-n参数指定每次将多少项,作为命令行参数。

$ xargs -n 1 find -name

上面命令指定将每一项(-n 1)标准输入作为命令行参数,分别执行一次命令(find -name)。

下面是另一个例子。

$ echo {0..9} | xargs -n 2 echo
0 1
2 3
4 5
6 7
8 9

上面命令指定,每两个参数运行一次echo命令。所以,10个阿拉伯数字运行了五次echo命令,输出了五行。

-I 参数

如果xargs要将命令行参数传给多个命令,可以使用-I参数。

-I指定每一项命令行参数的替代字符串。

$ cat foo.txt
one
two
three

$ cat foo.txt | xargs -I file sh -c 'echo file; mkdir file'
one 
two
three

$ ls 
one two three

上面代码中,foo.txt是一个三行的文本文件。我们希望对每一项命令行参数,执行两个命令(echomkdir),使用-I file表示file是命令行参数的替代字符串。执行命令时,具体的参数会替代掉echo file; mkdir file里面的两个file

–max-procs 参数

xargs默认只用一个进程执行命令。如果命令要执行多次,必须等上一次执行完,才能执行下一次。

--max-procs参数指定同时用多少个进程并行执行命令。--max-procs 2表示同时最多使用两个进程,--max-procs 0表示不限制进程数。

$ docker ps -q | xargs -n 1 --max-procs 0 docker kill

上面命令表示,同时关闭尽可能多的 Docker 容器,这样运行速度会快很多。

查找

find

find是最常见和最强大的查找命令,你可以用它找到任何你想找的文件。

find的使用格式如下:

$ find <指定目录> <指定条件> <指定动作>**
  - <指定目录>: 所要搜索的目录及其所有子目录。默认为当前目录。
  - <指定条件>: 所要搜索的文件的特征。
  - <指定动作>: 对搜索结果进行特定的处理。

find的使用实例:

$ find . -name 'my*'
搜索当前目录(含子目录,以下同)中,所有文件名以my开头的文件。
$ find . -name 'my*' -ls
搜索当前目录中,所有文件名以my开头的文件,并显示它们的详细信息。
$ find . -type f -mmin -10
搜索当前目录中,所有过去10分钟中更新过的普通文件。如果不加-type f参数,则搜索普通文件+特殊文件+目录。

locate

locate命令其实是”find -name”的另一种写法,但是要比后者快得多,原因在于它不搜索具体目录,而是搜索一个数据库(/var/lib/locatedb),这个数据库中含有本地所有文件信息。Linux系统自动创建这个数据库,并且每天自动更新一次,所以使用locate命令查不到最新变动过的文件。为了避免这种情况,可以在使用locate之前,先使用updatedb命令,手动更新数据库。

locate命令的使用实例:

$ locate /etc/sh
搜索etc目录下所有以sh开头的文件。
$ locate ~/m
搜索用户主目录下,所有以m开头的文件。
$ locate -i ~/m
搜索用户主目录下,所有以m开头的文件,并且忽略大小写。

whereis

whereis命令只能用于程序名的搜索,而且只搜索二进制文件(参数-b)、man说明文件(参数-m)和源代码文件(参数-s)。如果省略参数,则返回所有信息。

whereis命令的使用实例:

$ whereis grep

which

which命令的作用是,在PATH变量指定的路径中,搜索某个系统命令的位置,并且返回第一个搜索结果。也就是说,使用which命令,就可以看到某个系统命令是否存在,以及执行的到底是哪一个位置的命令。

which命令的使用实例:

$ which grep

type

type命令其实不能算查找命令,它是用来区分某个命令到底是由shell自带的,还是由shell外部的独立二进制文件提供的。

type命令的使用实例:

$ type cd
系统会提示,cd是shell的自带命令(build-in)。
$ type grep
系统会提示,grep是一个外部命令,并显示该命令的路径。

shell 示例

基本语法

!/bin/bash

# if test []
read -p "请输入文件名:" filename
if [ -d $filename ]; then
    ls -al $filename
elif [ -x $filename ]; then
    echo 这是一个可执行文件
else
    echo 这不是一个可执行文件
fi

# select
echo "请选择你今晚想吃啥:"
select food in "宫保鸡丁" "羊腰子" "小龙虾" "鸡肉卷"
do
    echo "那我们一起去吃$food吧"
    break
done
echo "那我们一起去吃$food吧"


# case
echo -e "yes?:\c"
read option
case $option in 
    yes | YES | y | Y) echo "那么开始咯";;
    no | NO | N | n) echo "那么下次吧";;
    *) echo "输入错误哦"
esac

# for
for file in 1 2 3	
do 
    echo -e "$file\t\c"
done

# while
count=1
sum=0
while test $count -le 100
do 
    ((sum+=count))
    let count+=1
done
echo $sum $count

# until
count=1
sum=0
until [ $count -gt 100 ]
do 
    ((sum+=count))
    let count+=1
done
echo $sum $count


function
function hello () {  
    echo hello
}
hello

# 函数中的变量
function fun(){
    local a=10  # 去掉local 则会影响main中取值
    echo "a in fun:"$a
}
a=5
echo "a in main:"$a
fun
echo "a in main:"$a
exit 0 

常用脚本

1 清除日志

#!/bin/bash
#清除日志脚本
LOG_DIR=/var/log 
if [ $UID -ne 0 ];then
    echo "Must be root to run this script"
   	exit 1
fi
cd $LOG_DIR || {
   echo "Cannot change to necessary directory." >&2   ## 输出到标准错误
   exit 1
}
 
cat /dev/null > message && echo "Logs cleaned up." #清理成功打印输出日志
#  message 是路径下的文件 ,我们用/dev/null 来清空内容
#/dev/null 还可以将一些非标准的输入流写入到 /dev/null,这样来可以屏蔽掉我们想展示的东西
exit 0
#退出之前返回0表示成功,返回1表示失败

/dev/null : 在类Unix系统中,/dev/null,或称空设备,是一个特殊的设备文件,它丢弃一切写入其中的数据(但报告写入操作成功),读取它则会立即得到一个EOF。在程序员行话,尤其是Unix行话中,/dev/null 被称为位桶(bit bucket)或者黑洞(black hole)。

2 判断参数数量,不匹配就打印使用方式,然后退出

if [ $# -ne 2 ];then
	echo "Usage: sh $0 a b"
	echo "Please run script as above format"
fi

常用命令示例

系统信息

uname -m 显示机器的处理器架构 uname -r 显示正在使用的内核版本 cat /proc/cpuinfo 显示CPU info的信息 cat /proc/interrupts 显示中断 cat /proc/meminfo 校验内存使用 cat /proc/swaps 显示哪些swap被使用 cat /proc/version 显示内核的版本 cat /proc/net/dev 显示网络适配器及统计 cat /proc/mounts 显示已加载的文件系统 date 显示系统日期 date 041217002007.00 设置日期和时间 - 月日时分年.秒 clock -w 将时间修改保存到 BIOS

系统的关机、重启以及登出

shutdown -h now 关闭系统 init 0 关闭系统 telinit 0 关闭系统 shutdown -h hours:minutes & 按预定时间关闭系统 shutdown -c 取消按预定时间关闭系统 shutdown -r now 重启 reboot 重启 logout 注销

文件和目录

cd ~user1 进入user1的主目录 cd - 返回上次所在的目录 pwd 显示工作路径 tree 显示文件和目录由根目录开始的树形结构 tree -L 1 -d /home/omc/ftl 只显示一层目录 mkdir dir1 dir2 同时创建两个目录 mkdir -p /tmp/dir1/dir2 创建一个目录树 rm -f file1 删除一个叫做 ‘file1’ 的文件’ rmdir dir1 删除一个叫做 ‘dir1’ 的目录’ rm -rf dir1 删除一个叫做 ‘dir1’ 的目录并同时删除其内容 rm -rf dir1 dir2 同时删除两个目录及它们的内容 mv dir1 new_dir 重命名/移动 一个目录 cp file1 file2 复制一个文件 cp dir/* . 复制一个目录下的所有文件到当前工作目录 cp -a /tmp/dir1 . 复制一个目录到当前工作目录 cp -a dir1 dir2 复制一个目录 ln -s file1 lnk1 创建一个指向文件或目录的软链接 ln file1 lnk1 创建一个指向文件或目录的物理链接 touch -t 0712250000 file1 修改一个文件或目录的时间戳 - (YYMMDDhhmm) file file1 outputs the mime type of the file as text iconv -l 列出已知的编码 iconv -f fromEncoding -t toEncoding inputFile > outputFile creates a new from the given input file by assuming it is encoded in fromEncoding and converting it to toEncoding. find . -maxdepth 1 -name *.jpg -print -exec convert “{}” -resize 80x60 “thumbs/{}” \; batch resize files in the current directory and send them to a thumbnails directory (requires convert from Imagemagick)

文件搜索

find / -name file1 从 ‘/’ 开始进入根文件系统搜索文件和目录 find / -user user1 搜索属于用户 ‘user1’ 的文件和目录 find /home/user1 -name *.bin 在目录 ‘/ home/user1’ 中搜索带有’.bin’ 结尾的文件 find /usr/bin -type f -atime +100 搜索在过去100天内未被使用过的执行文件 find /usr/bin -type f -mtime -10 搜索在10天内被创建或者修改过的文件 find / -name *.rpm -exec chmod 755 ‘{}’ \; 搜索以 ‘.rpm’ 结尾的文件并定义其权限 find / -xdev -name *.rpm 搜索以 ‘.rpm’ 结尾的文件,忽略光驱、捷盘等可移动设备 locate *.ps 寻找以 ‘.ps’ 结尾的文件 - 先运行 ‘updatedb’ 命令 whereis halt 显示一个二进制文件、源码或man的位置 which halt 显示一个二进制文件或可执行文件的完整路径

挂载一个文件系统

mount /dev/hda2 /mnt/hda2 挂载一个叫做hda2的盘 - 确定目录 ‘/ mnt/hda2’ 已经存在 umount /dev/hda2 卸载一个叫做hda2的盘 - 先从挂载点 ‘/ mnt/hda2’ 退出 fuser -km /mnt/hda2 当设备繁忙时强制卸载 umount -n /mnt/hda2 运行卸载操作而不写入 /etc/mtab 文件- 当文件为只读或当磁盘写满时非常有用 mount /dev/fd0 /mnt/floppy 挂载一个软盘 mount /dev/cdrom /mnt/cdrom 挂载一个cdrom或dvdrom mount /dev/hdc /mnt/cdrecorder 挂载一个cdrw或dvdrom mount /dev/hdb /mnt/cdrecorder 挂载一个cdrw或dvdrom mount -o loop file.iso /mnt/cdrom 挂载一个文件或ISO镜像文件 mount -t vfat /dev/hda5 /mnt/hda5 挂载一个Windows FAT32文件系统 mount /dev/sda1 /mnt/usbdisk 挂载一个usb 捷盘或闪存设备 mount -t smbfs -o username=user,password=pass //WinClient/share /mnt/share 挂载一个windows网络共享

磁盘空间

df -h 显示已经挂载的分区列表 ls -lSr |more 以尺寸大小排列文件和目录 du -sh dir1 估算目录 ‘dir1’ 已经使用的磁盘空间’ du -sk * | sort -rn 以容量大小为依据依次显示文件和目录的大小 rpm -q -a –qf ‘%10{SIZE}t%{NAME}n’ | sort -k1,1n 以大小为依据依次显示已安装的rpm包所使用的空间 (fedora, redhat类系统) dpkg-query -W -f=’${Installed-Size;10}t${Package}n’ | sort -k1,1n 以大小为依据显示已安装的deb包所使用的空间 (ubuntu, debian类系统)

用户和群组

groupadd group_name 创建一个新用户组 groupdel group_name 删除一个用户组 groupmod -n new_group_name old_group_name 重命名一个用户组 useradd -c “Name Surname “ -g admin -d /home/user1 -s /bin/bash user1 创建一个属于 “admin” 用户组的用户 useradd user1 创建一个新用户 userdel -r user1 删除一个用户 ( ‘-r’ 排除主目录) usermod -c “User FTP” -g system -d /ftp/user1 -s /bin/nologin user1 修改用户属性 passwd 修改口令 passwd user1 修改一个用户的口令 (只允许root执行) chage -E 2005-12-31 user1 设置用户口令的失效期限 pwck 检查 ‘/etc/passwd’ 的文件格式和语法修正以及存在的用户 grpck 检查 ‘/etc/passwd’ 的文件格式和语法修正以及存在的群组 newgrp group_name 登陆进一个新的群组以改变新创建文件的预设群组

文件的权限

ls -lh 显示权限 ls /tmp | pr -T5 -W$COLUMNS 将终端划分成5栏显示 chmod ugo+rwx directory1 设置目录的所有人(u)、群组(g)以及其他人(o)以读(r )、写(w)和执行(x)的权限 chmod go-rwx directory1 删除群组(g)与其他人(o)对目录的读写执行权限 chown user1 file1 改变一个文件的所有人属性 chown -R user1 directory1 改变一个目录的所有人属性并同时改变改目录下所有文件的属性 chgrp group1 file1 改变文件的群组 chown user1:group1 file1 改变一个文件的所有人和群组属性 find / -perm -u+s 罗列一个系统中所有使用了SUID控制的文件 chmod u+s /bin/file1 设置一个二进制文件的 SUID 位 - 运行该文件的用户也被赋予和所有者同样的权限 chmod u-s /bin/file1 禁用一个二进制文件的 SUID位 chmod g+s /home/public 设置一个目录的SGID 位 - 类似SUID ,不过这是针对目录的 chmod g-s /home/public 禁用一个目录的 SGID 位 chmod o+t /home/public 设置一个文件的 STIKY 位 - 只允许合法所有人删除文件 chmod o-t /home/public 禁用一个目录的 STIKY 位

文件的特殊属性

chattr +a file1 只允许以追加方式读写文件 chattr +c file1 允许这个文件能被内核自动压缩/解压 chattr +d file1 在进行文件系统备份时,dump程序将忽略这个文件 chattr +i file1 设置成不可变的文件,不能被删除、修改、重命名或者链接 chattr +s file1 允许一个文件被安全地删除 chattr +S file1 一旦应用程序对这个文件执行了写操作,使系统立刻把修改的结果写到磁盘 chattr +u file1 若文件被删除,系统会允许你在以后恢复这个被删除的文件 lsattr 显示特殊的属性

打包和压缩文件

bunzip2 file1.bz2 解压一个叫做 ‘file1.bz2’的文件 bzip2 file1 压缩一个叫做 ‘file1’ 的文件 gunzip file1.gz 解压一个叫做 ‘file1.gz’的文件 gzip file1 压缩一个叫做 ‘file1’的文件 gzip -9 file1 最大程度压缩 rar a file1.rar test_file 创建一个叫做 ‘file1.rar’ 的包 rar a file1.rar file1 file2 dir1 同时压缩 ‘file1’, ‘file2’ 以及目录 ‘dir1’ rar x file1.rar 解压rar包 unrar x file1.rar 解压rar包 tar -cvf archive.tar file1 创建一个非压缩的 tarball tar -cvf archive.tar file1 file2 dir1 创建一个包含了 ‘file1’, ‘file2’ 以及 ‘dir1’的档案文件 tar -tf archive.tar 显示一个包中的内容 tar -xvf archive.tar 释放一个包 tar -xvf archive.tar -C /tmp 将压缩包释放到 /tmp目录下 tar -cvfj archive.tar.bz2 dir1 创建一个bzip2格式的压缩包 tar -jxvf archive.tar.bz2 解压一个bzip2格式的压缩包 tar -cvfz archive.tar.gz dir1 创建一个gzip格式的压缩包 tar -zxvf archive.tar.gz 解压一个gzip格式的压缩包 zip file1.zip file1 创建一个zip格式的压缩包 zip -r file1.zip file1 file2 dir1 将几个文件和目录同时压缩成一个zip格式的压缩包 unzip file1.zip 解压一个zip格式压缩包

DEB 包

dpkg -i package.deb 安装/更新一个 deb 包 dpkg -r package_name 从系统删除一个 deb 包 dpkg -l 显示系统中所有已经安装的 deb 包 dpkg -l | grep httpd 显示所有名称中包含 “httpd” 字样的deb包 dpkg -s package_name 获得已经安装在系统中一个特殊包的信息 dpkg -L package_name 显示系统中已经安装的一个deb包所提供的文件列表 dpkg –contents package.deb 显示尚未安装的一个包所提供的文件列表 dpkg -S /bin/ping 确认所给的文件由哪个deb包提供

APT 软件工具

apt-get install package_name 安装/更新一个 deb 包 apt-cdrom install package_name 从光盘安装/更新一个 deb 包 apt-get update 升级列表中的软件包 apt-get upgrade 升级所有已安装的软件 apt-get remove package_name 从系统删除一个deb包 apt-get check 确认依赖的软件仓库正确 apt-get clean 从下载的软件包中清理缓存 apt-cache search searched-package 返回包含所要搜索字符串的软件包名称

查看文件内容

cat file1 从第一个字节开始正向查看文件的内容 tac file1 从最后一行开始反向查看一个文件的内容 more file1 查看一个长文件的内容 less file1 类似于 ‘more’ 命令,但是它允许在文件中和正向操作一样的反向操作 head -2 file1 查看一个文件的前两行 tail -2 file1 查看一个文件的最后两行 tail -f /var/log/messages 实时查看被添加到一个文件中的内容

文本处理

cat file1 file2 … | command <> file1_in.txt_or_file1_out.txt general syntax for text manipulation using PIPE, STDIN and STDOUT cat file1 | command( sed, grep, awk, grep, etc…) > result.txt 合并一个文件的详细说明文本,并将简介写入一个新文件中 cat file1 | command( sed, grep, awk, grep, etc…) » result.txt 合并一个文件的详细说明文本,并将简介写入一个已有的文件中 grep Aug /var/log/messages 在文件 ‘/var/log/messages’中查找关键词”Aug” grep ^Aug /var/log/messages 在文件 ‘/var/log/messages’中查找以”Aug”开始的词汇 grep [0-9] /var/log/messages 选择 ‘/var/log/messages’ 文件中所有包含数字的行 grep Aug -R /var/log/* 在目录 ‘/var/log’ 及随后的目录中搜索字符串”Aug” sed ‘s/stringa1/stringa2/g’ example.txt 将example.txt文件中的 “string1” 替换成 “string2” sed ‘/^$/d’ example.txt 从example.txt文件中删除所有空白行 sed ‘/ #/d; /^$/d’ example.txt 从example.txt文件中删除所有注释和空白行 echo ‘esempio’ | tr ‘[:lower:]’ ‘[:upper:]’ 合并上下单元格内容 sed -e ‘1d’ result.txt 从文件example.txt 中排除第一行 sed -n ‘/stringa1/p’ 查看只包含词汇 “string1”的行 sed -e ‘s/ *$//’ example.txt 删除每一行最后的空白字符 sed -e ‘s/stringa1//g’ example.txt 从文档中只删除词汇 “string1” 并保留剩余全部 sed -n ‘1,5p;5q’ example.txt 查看从第一行到第5行内容 sed -n ‘5p;5q’ example.txt 查看第5行 sed -e ‘s/00/0/g’ example.txt 用单个零替换多个零 cat -n file1 标示文件的行数 cat example.txt | awk ‘NR%2==1’ 删除example.txt文件中的所有偶数行 echo a b c | awk ‘{print $1}’ 查看一行第一栏 echo a b c | awk ‘{print $1,$3}’ 查看一行的第一和第三栏 paste file1 file2 合并两个文件或两栏的内容 paste -d ‘+’ file1 file2 合并两个文件或两栏的内容,中间用”+”区分 sort file1 file2 排序两个文件的内容 sort file1 file2 | uniq 取出两个文件的并集(重复的行只保留一份) sort file1 file2 | uniq -u 删除交集,留下其他的行 sort file1 file2 | uniq -d 取出两个文件的交集(只留下同时存在于两个文件中的文件) comm -1 file1 file2 比较两个文件的内容只删除 ‘file1’ 所包含的内容 comm -2 file1 file2 比较两个文件的内容只删除 ‘file2’ 所包含的内容 comm -3 file1 file2 比较两个文件的内容只删除两个文件共有的部分

字符设置和文件格式转换

dos2unix filedos.txt fileunix.txt 将一个文本文件的格式从MSDOS转换成UNIX unix2dos fileunix.txt filedos.txt 将一个文本文件的格式从UNIX转换成MSDOS recode ..HTML < page.txt > page.html 将一个文本文件转换成html recode -l | more 显示所有允许的转换格式

文件系统分析

badblocks -v /dev/hda1 检查磁盘hda1上的坏磁块 fsck /dev/hda1 修复/检查hda1磁盘上linux文件系统的完整性 fsck.ext2 /dev/hda1 修复/检查hda1磁盘上ext2文件系统的完整性 e2fsck /dev/hda1 修复/检查hda1磁盘上ext2文件系统的完整性 e2fsck -j /dev/hda1 修复/检查hda1磁盘上ext3文件系统的完整性 fsck.ext3 /dev/hda1 修复/检查hda1磁盘上ext3文件系统的完整性 fsck.vfat /dev/hda1 修复/检查hda1磁盘上fat文件系统的完整性 fsck.msdos /dev/hda1 修复/检查hda1磁盘上dos文件系统的完整性 dosfsck /dev/hda1 修复/检查hda1磁盘上dos文件系统的完整性

初始化一个文件系统

mkfs /dev/hda1 在hda1分区创建一个文件系统 mke2fs /dev/hda1 在hda1分区创建一个linux ext2的文件系统 mke2fs -j /dev/hda1 在hda1分区创建一个linux ext3(日志型)的文件系统 mkfs -t vfat 32 -F /dev/hda1 创建一个 FAT32 文件系统 fdformat -n /dev/fd0 格式化一个软盘 mkswap /dev/hda3 创建一个swap文件系统

备份

dump -0aj -f /tmp/home0.bak /home 制作一个 ‘/home’ 目录的完整备份 dump -1aj -f /tmp/home0.bak /home 制作一个 ‘/home’ 目录的交互式备份 restore -if /tmp/home0.bak 还原一个交互式备份 rsync -rogpav –delete /home /tmp 同步两边的目录 rsync -rogpav -e ssh –delete /home ip_address:/tmp 通过SSH通道rsync rsync -az -e ssh –delete ip_addr:/home/public /home/local 通过ssh和压缩将一个远程目录同步到本地目录 rsync -az -e ssh –delete /home/local ip_addr:/home/public 通过ssh和压缩将本地目录同步到远程目录 dd bs=1M if=/dev/hda | gzip | ssh user@ip_addr ‘dd of=hda.gz’ 通过ssh在远程主机上执行一次备份本地磁盘的操作 dd if=/dev/sda of=/tmp/file1 备份磁盘内容到一个文件 tar -Puf backup.tar /home/user 执行一次对 ‘/home/user’ 目录的交互式备份操作 ( cd /tmp/local/ && tar c . ) | ssh -C user@ip_addr ‘cd /home/share/ && tar x -p’ 通过ssh在远程目录中复制一个目录内容 ( tar c /home ) | ssh -C user@ip_addr ‘cd /home/backup-home && tar x -p’ 通过ssh在远程目录中复制一个本地目录 tar cf - . | (cd /tmp/backup ; tar xf - ) 本地将一个目录复制到另一个地方,保留原有权限及链接 find /home/user1 -name ‘.txt’ | xargs cp -av –target-directory=/home/backup/ –parents 从一个目录查找并复制所有以 ‘.txt’ 结尾的文件到另一个目录 find /var/log -name ‘.log’ | tar cv –files-from=- | bzip2 > log.tar.bz2 查找所有以 ‘.log’ 结尾的文件并做成一个bzip包 dd if=/dev/hda of=/dev/fd0 bs=512 count=1 做一个将 MBR (Master Boot Record)内容复制到软盘的动作 dd if=/dev/fd0 of=/dev/hda bs=512 count=1 从已经保存到软盘的备份中恢复MBR内容

光盘

cdrecord -v gracetime=2 dev=/dev/cdrom -eject blank=fast -force 清空一个可复写的光盘内容 mkisofs /dev/cdrom > cd.iso 在磁盘上创建一个光盘的iso镜像文件 mkisofs /dev/cdrom | gzip > cd_iso.gz 在磁盘上创建一个压缩了的光盘iso镜像文件 mkisofs -J -allow-leading-dots -R -V “Label CD” -iso-level 4 -o ./cd.iso data_cd 创建一个目录的iso镜像文件 cdrecord -v dev=/dev/cdrom cd.iso 刻录一个ISO镜像文件 gzip -dc cd_iso.gz | cdrecord dev=/dev/cdrom - 刻录一个压缩了的ISO镜像文件 mount -o loop cd.iso /mnt/iso 挂载一个ISO镜像文件 cd-paranoia -B 从一个CD光盘转录音轨到 wav 文件中 cd-paranoia – “-3” 从一个CD光盘转录音轨到 wav 文件中(参数-3) cdrecord –scanbus 扫描总线以识别scsi通道 dd if=/dev/hdc | md5sum 校验一个设备的md5sum编码,例如一张 CD

网络

ifconfig eth0 显示一个以太网卡的配置 ifup eth0 启用一个 ‘eth0’ 网络设备 ifdown eth0 禁用一个 ‘eth0’ 网络设备 ifconfig eth0 192.168.1.1 netmask 255.255.255.0 控制IP地址 ifconfig eth0 promisc 设置 ‘eth0’ 成混杂模式以嗅探数据包 (sniffing) dhclient eth0 以dhcp模式启用 ‘eth0’ route -n show routing table route add -net 0/0 gw IP_Gateway configura default gateway route add -net 192.168.0.0 netmask 255.255.0.0 gw 192.168.1.1 configure static route to reach network ‘192.168.0.0/16’ route del 0/0 gw IP_gateway remove static route echo “1” > /proc/sys/net/ipv4/ip_forward activate ip routing hostname show hostname of system host www.example.com lookup hostname to resolve name to ip address and viceversa nslookup www.example.com lookup hostname to resolve name to ip address and viceversa ip link show show link status of all interfaces mii-tool eth0 show link status of ‘eth0’ ethtool eth0 show statistics of network card ‘eth0’ netstat -tup show all active network connections and their PID netstat -tupl show all network services listening on the system and their PID tcpdump tcp port 80 show all HTTP traffic iwlist scan show wireless networks iwconfig eth1 show configuration of a wireless network card hostname show hostname host www.example.com lookup hostname to resolve name to ip address and viceversa nslookup www.example.com lookup hostname to resolve name to ip address and viceversa whois www.example.com lookup on Whois database