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 後面加個數字 替換成匹配的第一個字段。