linux常用文件操作命令集


linux常用文件操作命令集
 
1.创建特定大小的文件dd
[wang@localhost 桌面]$ dd if=/dev/zero of=test.data bs=1K count=2
2+0 records in
2+0 records out
2048 bytes (2.0 kB) copied,0.00112496 秒,1.8 MB/秒
其中if表示输入文件,of表示输出文件,bs表示单位块大小,count表示需要复制的块数。
创建空白文件就用touch filename
 
2.文件的交集和差集comm
[wang@localhost 桌面]$ sort b.txt -o b.txt 
[wang@localhost 桌面]$ sort a.txt -o a.txt 
[wang@localhost 桌面]$ comm a.txt b.txt 
 
a
b
c
d
e
f
g
i
第一列包含只在a.txt出现的行,第二列包含只在b.txt出现的行,第三列包含在a.txt和b.txt出现的行
[wang@localhost 桌面]$ comm a.txt b.txt -1 -2
a
c
d
f
-1表示干掉第一列,-2表示干掉第二列,用于取交集。
 
3.创建长目录mkdir
[wang@localhost 桌面]$ mkdir -p ./william/wang/2013
此命令会依次创建william,wang,2013目录
 
4.查看文件信息file
[wang@localhost 桌面]$ file shell.sh 
shell.sh: Bourne-Again shell script text executable
[wang@localhost 桌面]$ file -b shell.sh 
Bourne-Again shell script text executable    //只列出文件类型
 
5.查找文件差异并进行修补diff
[wang@localhost 桌面]$ diff -u a.txt b.txt 
--- a.txt 2013-03-26 14:17:00.265890952 +0800
+++ b.txt 2013-03-26 14:16:55.439744576 +0800
@@ -1,8 +1,5 @@
-
 a
-b
 c
 d
-e
 f
-g
+i
[wang@localhost 桌面]$ diff -u a.txt b.txt > c.patch
[wang@localhost 桌面]$ patch -p1 b.txt < c.patch 
missing header for unified diff at line 3 of patch
patching file b.txt
Reversed (or previously applied) patch detected!  Assume -R? [n] y
[wang@localhost 桌面]$ cat b.txt
 
a
b
c
d
e
f
g
现在b.txt和a.txt内容一样了。
 
6.打印前面或后面几行
[wang@localhost 桌面]$ head -n 3 b.txt
 
a
b
[wang@localhost 桌面]$ tail -n -2 b.txt
f
g
[wang@localhost 桌面]$ tail -f /var/log/messages
tail: 无法打开 “/var/log/messages” 读取数据: 权限不够
tail: no files remaining
[root@localhost 桌面]# tail -f /var/log/messages    //跟踪日志
Mar 26 13:57:13 localhost dhclient: bound to 192.168.126.148 -- renewal in 706 seconds.
Mar 26 14:08:59 localhost dhclient: DHCPREQUEST on eth0 to 192.168.126.254 port 67
Mar 26 14:08:59 localhost dhclient: DHCPACK from 192.168.126.254
Mar 26 14:08:59 localhost dhclient: bound to 192.168.126.148 -- renewal in 876 seconds.
也可以这样用:[root@localhost 桌面]# dmesg | tail -f
 
7.只列出目录
[wang@localhost 桌面]$ ls -d */
mm/  
[wang@localhost 桌面]$ ls -l | grep "^d"
drwxrwxr-x.  2 wang wang   4096 01-25 19:33 mm
 
8.最近的两个目录切换
[wang@localhost 桌面]$ cd -
/home/wang/project
[wang@localhost project]$ cd -
/home/wang/桌面
[wang@localhost 桌面]$ 
 
9.查找匹配的文件
[wang@localhost 桌面]$ grep -l "bin" . -r
./mm/test.sh
./shell.sh
./bt.sh
./test1.sh
./startup.x
 
10.切分文件
[wang@localhost 桌面]$ cut -f2,3 -d ":" /etc/passwd
x:0
x:1
x:2
 
11.查找文件并操作
find 路径 -name "文件" -exec "command" {} \;
[wang@localhost 桌面]$ find . -name "a.txt" -exec cp {} /home/wang/project/ \;
[wang@localhost 桌面]$ ls /home/wang/project/
 
12.替换sed
[wang@localhost 桌面]$ echo WO WO WO | sed 's/WO/wo/2g'
WO wo wo
从第二个匹配的地方开始替换,不要2的话,就全部替换。
[wang@localhost 桌面]$ echo WO WO WO | sed 's/WO/wo/g'
wo wo wo
[wang@localhost 桌面]$ echo WO WO WO | sed 's/WO/wo/'
wo WO WO
[wang@localhost 桌面]$ echo linux is 2 | sed 's/is \([0-9]\)/\1/' 
linux 2
is 后面加个数字 替换成匹配的第一个字段。
 

相关内容

    暂无相关文章