linux sed使用

轉載地址:https://www.cnblogs.com/taosim/articles/3761007.html

salt '*' cmd.run 'sed -i 's/SELINUX\=enforcing/SELINUX\=disabled/g' /etc/sysconfig/selinux'

....

 http://hi.baidu.com/gz_gzhao/item/3c7cacfacfa494c40cd1c865

#! /bin/bash

echo "測試寫文件"
cat>test1<<EOF
這是一個由shell創建的文件
this is a file created by shell.
we want to make a good world.
EOF

其中,<<EOF 表示當遇到EOF時結束輸入。

cat>test1<<EOF 這間沒有空格

http://kevingo75.blogspot.com/2011/08/shell-script-echoapppend.html

在編寫Shell Script時,如果你有echo到某個檔案的需求,你希望寫入檔案時是以附加(append)的方式進行,而不是整個覆蓋的話,你可以使用【>>】來取代【>】: 

echo "aaa" >> /home/kevingo/example.txt 
echo "bbb" >> /home/kevingo/example.txt
 

如此一來,example.txt中的內容就會是: 
aaa 
bbb

====================================================

http://bbs.phpchina.com/blog-191373-187668.html

ctags:  linux perl shell perl  vi grep awk xargs  批量替換

方法1:
 
這兩天在構建一個應用的使用用到了maven,由於project很大,足足有700多個 pom.xml文件,更鬱悶的是在很多pom.xml文件裏都單獨指定了資源庫的url,我需要把這些資源庫的url統一指定到nexus本地中央庫.
手 工一個個改文件配置有點不太實際,所以google了一下,找到批量替換文件內容的好方法,命令結構如下:
find -name '要查找的文件名' | xargs perl -pi -e 's|被替換的字符串|替換後的字符串|g'下面這個例子就是將當前目錄及所有子目錄下的所有pom.xml文件中的http://repo1.maven.org/maven2; 替換爲http://localhost:8081/nexus/content/groups/public
find -name 'pom.xml' | xargs perl -pi -e 's|http://repo1.maven.org/maven2|http://localhost:8081/nexus/content /groups/public|g'這裏用到了Perl語言,
perl -pi -e 在Perl 命令中加上-e 選項,後跟一行代碼,那它就會像運行一個普通的Perl 腳本那樣運行該代碼.
從命令行中使用Perl 能夠幫助實現一些強大的、實時的轉換。認真研究正則表達式,並正確地使用,將會爲您省去大量的手工編輯工作。
find -name 'pom.xml' | xargs perl -pi -e 's|http://repo1.maven.org/maven2|http://localhost:8081/nexus/content/groups/public|g'
 
方法2:

Linux下批量替換多個文件中的字符串的簡單方法。用sed命令可以批量替換多個文件中的字符串。
用sed命令可以批量替換多個文件中的 字符串。 
sed -i "s/原字符串/新字符串/g" `grep 原字符串 -rl 所在目錄`
例如:我要把mahuinan替換 爲huinanma,執行命令: 
sed -i "s/mahuinan/huinanma/g" 'grep mahuinan -rl /www'
這是目前linux最簡單的批量替換字符串命令了!
具體格式如下: 
sed -i "s/oldString/newString/g"  `grep oldString -rl /path`
實例代碼:sed -i "s/大小多少/日月水火/g" `grep 大小多少 -rl /usr/aa`
sed -i "s/大小多少/日月水火/g" `grep 大小多少 -rl ./`

方法3:

在日程的開發過程中,可能大家會遇到將某個變量名修改 爲另一個變量名的情況,如果這個變量是一個局部變量的話,vi足以勝任,但是如果是某個全局變量的話,並且在很多文件中進行了使用,這個時候使用vi就是 一個不明智的選擇。這裏給出一個簡單的shell命令,可以一次性將所有文件中的指定字符串進行修改:
grep "abc" * -R | awk -F: '{print $1}' | sort | uniq | xargs sed -i 's/abc/abcde/g'


from: http://blog.zol.com.cn/1395/article_1394052.html

補充說明
sed -i "s/oldString/newString/g"  `grep oldString -rl /path`    
對多個文件的處理可能不支持,需要用 xargs, 搞定。
變種如下:
grep 
oldString -rl /path | xargs sed -i "s/oldString/newString/g" 

注意: 
在  `grep oldString -rl /path`    中 ` 爲1前邊的翻引號`,而不是enter 前的 '

 

 ==================

http://www.cnblogs.com/ggjucheng/archive/2013/01/13/2856901.html

簡介

sed 是一種在線編輯器,它一次處理一行內容。處理時,把當前處理的行存儲在臨時緩衝區中,稱爲“模式空間”(pattern space),接着用sed命令處理緩衝區中的內容,處理完成後,把緩衝區的內容送往屏幕。接着處理下一行,這樣不斷重複,直到文件末尾。文件內容並沒有 改變,除非你使用重定向存儲輸出。Sed主要用來自動編輯一個或多個文件;簡化對文件的反覆操作;編寫轉換程序等。

 

sed使用參數

複製代碼
複製代碼
[root@www ~]# sed [-nefr] [動作]
選項與參數:
-n :使用安靜(silent)模式。在一般 sed 的用法中,所有來自 STDIN 的數據一般都會被列出到終端上。但如果加上 -n 參數後,則只有經過sed 特殊處理的那一行(或者動作)纔會被列出來。
-e :直接在命令列模式上進行 sed 的動作編輯;
-f :直接將 sed 的動作寫在一個文件內, -f filename 則可以運行 filename 內的 sed 動作;
-r :sed 的動作支持的是延伸型正規表示法的語法。(默認是基礎正規表示法語法)
-i :直接修改讀取的文件內容,而不是輸出到終端。

動作說明: [n1[,n2]]function
n1, n2 :不見得會存在,一般代表『選擇進行動作的行數』,舉例來說,如果我的動作是需要在 1020 行之間進行的,則『 10,20[動作行爲] 』

function:
a :新增, a 的後面可以接字串,而這些字串會在新的一行出現(目前的下一行)~
c :取代, c 的後面可以接字串,這些字串可以取代 n1,n2 之間的行!
d :刪除,因爲是刪除啊,所以 d 後面通常不接任何咚咚;
i :插入, i 的後面可以接字串,而這些字串會在新的一行出現(目前的上一行);
p :列印,亦即將某個選擇的數據印出。通常 p 會與參數 sed -n 一起運行~
s :取代,可以直接進行取代的工作哩!通常這個 s 的動作可以搭配正規表示法!例如 1,20s/old/new/g 就是啦!
複製代碼
複製代碼

 

以行爲單位的新增/刪除


將 /etc/passwd 的內容列出並且列印行號,同時,請將第 2~5 行刪除!

[root@www ~]# nl /etc/passwd | sed '2,5d'
1 root:x:0:0:root:/root:/bin/bash
6 sync:x:5:0:sync:/sbin:/bin/sync
7 shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
.....(後面省略).....


sed 的動作爲 '2,5d' ,那個 d 就是刪除!因爲 2-5 行給他刪除了,所以顯示的數據就沒有 2-5 行羅~ 另外,注意一下,原本應該是要下達 sed -e 纔對,沒有 -e 也行啦!同時也要注意的是, sed 後面接的動作,請務必以 '' 兩個單引號括住喔!

只要刪除第 2 行

nl /etc/passwd | sed '2d' 

 

要刪除第 3 到最後一行

 nl /etc/passwd | sed '3,$d' 

 

在第二行後(亦即是加在第三行)加上『drink tea?』字樣!

[root@www ~]# nl /etc/passwd | sed '2a drink tea'
1 root:x:0:0:root:/root:/bin/bash
2 bin:x:1:1:bin:/bin:/sbin/nologin
drink tea
3 daemon:x:2:2:daemon:/sbin:/sbin/nologin
.....(後面省略).....

 

那如果是要在第二行前

 nl /etc/passwd | sed '2i drink tea' 

 

如果是要增加兩行以上,在第二行後面加入兩行字,例如『Drink tea or .....』與『drink beer?』

複製代碼
複製代碼
[root@www ~]# nl /etc/passwd | sed '2a Drink tea or ......\
> drink beer ?'
1 root:x:0:0:root:/root:/bin/bash
2 bin:x:1:1:bin:/bin:/sbin/nologin
Drink tea or ......
drink beer ?
3 daemon:x:2:2:daemon:/sbin:/sbin/nologin
.....(後面省略).....
複製代碼
複製代碼

每一行之間都必須要以反斜槓『 \ 』來進行新行的添加喔!所以,上面的例子中,我們可以發現在第一行的最後面就有 \ 存在。


以行爲單位的替換與顯示


將第2-5行的內容取代成爲『No 2-5 number』呢?

[root@www ~]# nl /etc/passwd | sed '2,5c No 2-5 number'
1 root:x:0:0:root:/root:/bin/bash
No 2-5 number
6 sync:x:5:0:sync:/sbin:/bin/sync
.....(後面省略).....


透過這個方法我們就能夠將數據整行取代了!

 

僅列出 /etc/passwd 文件內的第 5-7 行

[root@www ~]# nl /etc/passwd | sed -n '5,7p'
5 lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
6 sync:x:5:0:sync:/sbin:/bin/sync
7 shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown

可以透過這個 sed 的以行爲單位的顯示功能, 就能夠將某一個文件內的某些行號選擇出來顯示。

 

數據的搜尋並顯示

搜索 /etc/passwd有root關鍵字的行

複製代碼
複製代碼
nl /etc/passwd | sed '/root/p'
1  root:x:0:0:root:/root:/bin/bash
1  root:x:0:0:root:/root:/bin/bash
2  daemon:x:1:1:daemon:/usr/sbin:/bin/sh
3  bin:x:2:2:bin:/bin:/bin/sh
4  sys:x:3:3:sys:/dev:/bin/sh
5  sync:x:4:65534:sync:/bin:/bin/sync
....下面忽略 
複製代碼
複製代碼

如果root找到,除了輸出所有行,還會輸出匹配行。

 

使用-n的時候將只打印包含模板的行。

nl /etc/passwd | sed -n '/root/p'
1  root:x:0:0:root:/root:/bin/bash

 

數據的搜尋並刪除

刪除/etc/passwd所有包含root的行,其他行輸出

nl /etc/passwd | sed  '/root/d'
2  daemon:x:1:1:daemon:/usr/sbin:/bin/sh
3  bin:x:2:2:bin:/bin:/bin/sh
....下面忽略
#第一行的匹配root已經刪除了

 

 

 

數據的搜尋並執行命令

找到匹配模式eastern的行後,

搜索/etc/passwd,找到root對應的行,執行後面花括號中的一組命令,每個命令之間用分號分隔,這裏把bash替換爲blueshell,再輸出這行:

 nl /etc/passwd | sed -n '/root/{s/bash/blueshell/;p}'
 1  root:x:0:0:root:/root:/bin/blueshell

如果只替換/etc/passwd的第一個bash關鍵字爲blueshell,就退出

nl /etc/passwd | sed -n '/bash/{s/bash/blueshell/;p;q}'    
1  root:x:0:0:root:/root:/bin/blueshell

最後的q是退出。

 

數據的搜尋並替換

除了整行的處理模式之外, sed 還可以用行爲單位進行部分數據的搜尋並取代。基本上 sed 的搜尋與替代的與 vi 相當的類似!他有點像這樣:

sed 's/要被取代的字串/新的字串/g'

 

先觀察原始信息,利用 /sbin/ifconfig 查詢 IP

[root@www ~]# /sbin/ifconfig eth0
eth0 Link encap:Ethernet HWaddr 00:90:CC:A6:34:84
inet addr:192.168.1.100 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::290:ccff:fea6:3484/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
.....(以下省略).....


本機的ip是192.168.1.100。

 

將 IP 前面的部分予以刪除

[root@www ~]# /sbin/ifconfig eth0 | grep 'inet addr' | sed 's/^.*addr://g'
192.168.1.100 Bcast:192.168.1.255 Mask:255.255.255.0

接下來則是刪除後續的部分,亦即: 192.168.1.100 Bcast:192.168.1.255 Mask:255.255.255.0

將 IP 後面的部分予以刪除

[root@www ~]# /sbin/ifconfig eth0 | grep 'inet addr' | sed 's/^.*addr://g' | sed 's/Bcast.*$//g'
192.168.1.100

 

多點編輯

一條sed命令,刪除/etc/passwd第三行到末尾的數據,並把bash替換爲blueshell

nl /etc/passwd | sed -e '3,$d' -e 's/bash/blueshell/'
1  root:x:0:0:root:/root:/bin/blueshell
2  daemon:x:1:1:daemon:/usr/sbin:/bin/sh

-e表示多點編輯,第一個編輯命令刪除/etc/passwd第三行到末尾的數據,第二條命令搜索bash替換爲blueshell。

 

 

直接修改文件內容(危險動作)


sed 可以直接修改文件的內容,不必使用管道命令或數據流重導向! 不過,由於這個動作會直接修改到原始的文件,所以請你千萬不要隨便拿系統配置來測試! 我們還是使用下載的 regular_express.txt 文件來測試看看吧!

利用 sed 將 regular_express.txt 內每一行結尾若爲 . 則換成 !

[root@www ~]# sed -i 's/\.$/\!/g' regular_express.txt

 

利用 sed 直接在 regular_express.txt 最後一行加入『# This is a test』

[root@www ~]# sed -i '$a # This is a test' regular_express.txt

由於 $ 代表的是最後一行,而 a 的動作是新增,因此該文件最後新增『# This is a test』!

sed 的『 -i 』選項可以直接修改文件內容,這功能非常有幫助!舉例來說,如果你有一個 100 萬行的文件,你要在第 100 行加某些文字,此時使用 vim 可能會瘋掉!因爲文件太大了!那怎辦?就利用 sed 啊!透過 sed 直接修改/取代的功能,你甚至不需要使用 vim 去修訂!

 

參考 http://vbird.dic.ksu.edu.tw/linux_basic/0330regularex_2.php#sed

       http://www.cnblogs.com/stephen-liu74/archive/2011/11/17/2245130.html

 ==================

http://yidao620c.iteye.com/blog/1880974

4.1 sed命令基本用法

sed是一個非交互式文本編輯器,它可以對文本文件和標準輸入進行編輯,標準輸入可以是來自鍵盤輸入、文件重定向、字符串、變量、來自管道的文本等等。

sed從文本的一個文本行或標準輸入中讀取數據,將其複製到緩存區,然後讀取命令行或腳本的第一個命令,對此命令要求的行號進行編輯,重複此過程,直到命令行或腳本中所有命令都執行完了。sed可以一次性處理所有的編輯命令,非常高效

 

sed適用於下面三種場合:

* 編輯相對於交互式文本編輯器而言太大的場合

* 編輯命令太複雜,在交互式文本編輯器中難以輸入的情況

* 對文件掃描一遍,但是需要執行多個編輯函數的情況

 

sed只是對緩存區中原始文件的副本進行編輯,並不編輯原始文件。因此,如果需要保存更改內容,需要將輸出重定向到另一個文件,可以使用下面的命令:

sed 'sed命令' input_file > result_file

或者還有另一種方法就是 -w 選項,這個後面講到

 

有三種方式調用sed:

① 直接在shell命令行上調用

# sed [選項] 'sed命令' 輸入文件

② 將sed命令插入腳本文件後,通過sed命令調用腳本:

# sed [選項] -f sed腳本文件名 輸入文件

③ 將sed命令寫入腳本文件後,將其+x變成可執行

./sed腳本文件 輸入文件

第三種方式需要在文件頭部加上 #!/bin/sed

 

sed命令的常用選項:

-n    不打印所有行到標準輸出

-e    表示將下一個字符串解析爲sed編輯命令,如果只傳遞一個編輯命令,-e可以省略

-f     表示正在調用sed腳本文件

 

sed命令通常由定位文本行和sed編輯命令兩部分組成,sed編輯命令對定位到的行進行各種編輯處理

sed提供兩種方式定位文本行:

* 使用行號,指定一行或者行號範圍

* 使用正則表達式

 

sed命令定位文本行的方法:

選項意義
xx爲指定行號
x,y指定從x到y的行號範圍
/pattern/查詢包含模式的行
/pattern/pattern/查詢包含兩個模式的行
/pattern/,x從與pattern的匹配行到x號行之間的行
x,/pattern/從x號行到與pattern的匹配行之間的行
x,y!查詢不包含x和y行號的行

 

===================================分割線=======================

sed編輯命令表

選項意義
p打印匹配行
=打印匹配行號
a\在定位行之後追加文本信息
i\在定位行之前插入文本信息
d刪除定位行
c\用新文本替換定位行
s使用替換模式替換相應的模式
r從另一個文件中讀文本
w將文本寫入到另一個文件中
y變換字符
q第一個模式匹配完成後退出
l顯示與八進制ASCII碼等價的控制字符
{}在定位行執行的命令組
n讀取下一個輸入行,用下一個命令處理新的行
h將模式緩存區的文本複製到保持緩存區
H將模式緩存區的文本追加到保持緩存區
x互換模式緩存區和保持緩存區的內容
g將保持緩存區的內容複製到模式緩存區
G將保持緩存區的內容追加到模式緩存區

 

========================分割線============================

各個選項和編輯命令詳解:

1,sed命令的-n選項和p命令

# sed -n '1p' input

# sed '1p' input

從輸出可以看出,加了-n後標準輸出上只有第一行打印出來了,而不加-n時候,先打印第一行,然後打印整個文件內容。所以-n選項的意義是:不打印sed編輯內容也就是input的全部內容。只打印匹配的行

# sed -n '3,6p' input   --> 打印從3到6行

# sed -n '/certificate/p' input  --> 打印匹配模式行,注意大小寫是敏感的

 

2,sed命令的-e選項

由於sed不支持同時帶多個編輯命令的用法,因此需要用-e選項指定每個編輯命令

# sed -n -e '/Certificate/p' -e '/Certificate/=' input

 

3,sed命令的-f選項

-f選項只有調用sed腳本文件時才起作用,追加文本、插入文本、修改文本、刪除文本和替換文本等功能往往需要幾條sed命令才能完成,所以,往往將這些命令寫入sed腳本,然後調用sed腳本來完成。

下面是這個sed的腳本:

Sed代碼  收藏代碼
  1. #!/bin/sed -f  
  2. /file:/a\  
  3. We append a new line.\  
  4. We append another line.  

注:上面的/file:/a\中的\表示在換新行後添加內容,而下面內容中的\也表示換行。

 

4.2.2 sed文本定位的一組例子

1. 匹配元字符

如果目標字符串中包含元字符,需要使用轉義符\屏蔽其特殊意義。

# sed -n '/\./p' input --> 打印含有.的行

2. 使用元字符進行匹配

sed可以靈活使用正則表達式的元字符進行匹配,不過注意的是:$在正則表達式中表示行尾,但是在sed命令中卻表示最後一行,而寫在//中間的$就表示行尾了,哈哈。

# sed -n '$p' input --> 打印最後一行

# sed -n '/^$/p' input -> 打印空行

3. !符號

!表示取反,也就是不滿足條件的時候就處理

# sed -n '/.*this/!p' input  --> 打印不包含this的行

# sed -n '3,6!p' input --> 打印不在3至6行間的行

 

4.2.3 sed基本編輯命令的一組例子

1. 插入文本

插入文本和追加文本類似,區別僅僅是追加文本是在匹配行的後面插入,而插入文本是在匹配行的前面插入

sed插入文本符號位i\,插入文本的格式爲:

sed '指定地址 i\text' 輸入文件

新建名爲insert.sed的腳本,內容如下:

Bash代碼  收藏代碼
  1. #!/bin/sed -f   
  2. # this is comment  
  3. # date : 2013/06/02  
  4. # author : xiongneng  
  5. /this is/i\  
  6. We insert a new line #插入的文本內容  

 

 2. 修改文本

修改文本是指將所匹配的問本行用新文本代替,也就是隻能整行替換,sed修改文本符號位c\

sed '指定行 c\text' 輸入文件

 

3. 刪除文本

sed刪除文本命令可以將指定行或指定行範圍進行刪除,sed的刪除文本符號爲d

sed '指定行 d' 輸入文件

 

4.替換文本

sed替換文本將所匹配的文本行中找到的字符串用新的字符串去代替,常用。而上面的修改文本只能整行,sed替換文本符號爲s

sed -n 's/被替換的字符串/新的字符串/p' --> 只替換每行中第一次找到的

sed -n 's/被替換的字符串/新的字符串/gp' --> 替換每行中所有找到的

sed -n 's/被替換的字符串/新的字符串/np' --> 替換每行中第n次找到的

sed替換文本中有個重要的符號&,它表示保存被替換的字符串以供調用。

比如下面兩條命令等級:(都是將this字符串用括號括起來)

# sed -n 's/this/(&)/gp' input

# sed -n 's/this/(this)/gp' input

 

5. 寫入到一個新文件

上面提到的都是對緩存區中輸入文件的複製內容進行編輯,如果要保存編輯結果,需要將編輯後的文本重定向到另一個文件,sed寫入文件符號爲w,基本格式爲:

# sed -n '1,5 w output' input

# sed -n '/this/2 output' input

# sed -n 's/this/(&)/gw output' input  --> 將this加上括號後,匹配行寫入到output中去

注:這裏寫到新文件中的只有匹配的行修改後的數據,如果要整個文件內容都寫進去,使用重定向>> 或者>

 

6. 從文件中讀入文本內容

sed命令還可以將其他文件中的內容讀入,並附加在指定地址後,sed讀入文件的符號爲r

# sed '/this/r otherfile' input

 

7. 退出命令

sed命令的q選項表示完成指定地址匹配後立即退出

# sed -n '/this/p' input  --> 打印出匹配的全部字符串

# sed -n -e '/this/p' -e '/this/q' test.txt  --> 找到第一個匹配的打印後就立即退出

 

8. 變換命令

sed命令的y選項表示字符變換,它將一系列的字符變換爲相應的字符,逐個處理的

# sed 'y/被變換的字符序列/變換的字符序列/' 輸入文件

# sed 'y/12345/ABCDE' input --> 將input中1變成A,2變成B,3變成C,4變成D,5變成E

 

9. 顯示控制字符

sed 1命令可以顯示出文件中的控制字符,比如退格鍵、F1鍵、Shift鍵等

# sed -n '1,$1' input

 

10. 在定位行執行命令組

sed編輯命令中的{}可以指定在定位行上所執行的命令組,它的作用與sed的-e選項類似,都是爲了在定位行執行多個編輯命令。

下面的命令等價:

# sed -n -e '/this/p' -e '/this/q' test.txt 

# sed -n '/this/{p;q}' test.txt -->顯然這個更NB點

 

4.2.4 sed高級編輯命令的一組例子

1. 處理匹配行的下一行

sed編輯命令n的意義是讀取下一個輸入行,用n後面的一個命令處理該行,由於此時通常有個多個編輯命令,所以命令n需要與{}配合使用

# sed '/this is/{n;s/her/him/;}' input --> 找到this is關鍵詞那行,然後將它下一行的her替換成him

 

2. sed緩存區的處理

前面提到的所有編輯命令都是將輸入文件複製到緩存區,對緩存區的複製內容進行處理。實際上,sed有兩個緩存區,模式緩存區 Pattern Buffer 和保持緩存區 Hold Buffer。前面都是Pattern Buffer,而保持緩存區是另一個內存空間,sed的一些編輯命令可以對保持緩存區進行處理,並與模式緩存區的內容互換

# sed h、x、G命令的用法

# sed  '/subject/h; /object/x; $G' input

解釋下:

第一個h命令是將模式緩存區內容複製到保持緩存區,也就是說當找到subject的行的時候,就將該行復制到Hold Buffer,如果該行有object關鍵詞就將模式緩存區和保持緩存內容互換後輸出模式緩存區內容,第三條命令表示如果是到了最後一行,就直接輸出保持緩存區內容。

 

h和H、g和G是兩組對應的命令

h和H命令是將模式緩存區內容替換掉保持緩存區內容,不過h是副本,即將保持緩存區的就內容覆蓋掉,而H是追加,即在保持緩存區內容上增加新的內容

g和G是將保持緩存區內容替換掉模式緩存區內容,同樣,g是副本、G是追加。

 

3.利用分號;分割多個編輯命令,這個比起-e選項更NB一點。^_^

# sed  '/subject/h; /object/x; $G' input

 

 ================

http://bbs.chinaunix.net/thread-2051464-1-1.html

 

 

> 把輸出內容放到你的文件中,(前清空在輸入)
>>同上(但是表示追加)

 

==========================================

http://blog.csdn.net/lzyzuixin/article/details/7638979

比如,要將目錄/modules下面所有文件中的zhangsan都修改成lisi,這樣做:

sed -i "s/zhangsan/lisi/g" `grep zhangsan -rl /modules`

解釋一下:

-i 表示inplace edit,就地修改文件
-r 表示搜索子目錄
-l 表示輸出匹配的文件名


這個命令組合很強大,要注意備份文件。


(1)sed 'y/1234567890/ABCDEFGHIJ/' test_sed
sed 'y/1234567890/ABCDEFGHIJ/' filename
ABCDEFGHIJ
BCDEFGHIJA
CDEFGHIJAB
DEFGHIJABC
注意變換關係是按兩個list的位置對應變換

其中:test_sed的內容是:
1234567890
2345678901
3456789012
4567890123


(2)
替換每行所有匹配
sed 's/01/Ab/g' test_sed
1234567890
23456789Ab
3456789Ab2
456789Ab23

注意:第一行的0,1沒有分別替換爲A,b


刪除:d命令  

  •      $ sed '2d' example-----刪除example文件的第二行。
  •      $ sed '2,$d' example-----刪除example文件的第二行到末尾所有行。
  •      $ sed '$d' example-----刪除example文件的最後一行。
  •      $ sed '/test/'d example-----刪除example文件所有包含test的行。


替換:s命令  

  •      $ sed 's/test/mytest/g' example-----在整行範圍內把test替換爲mytest。如果沒有g標記,則只有每行第一個匹配的test被替換成mytest。
  •      $ sed -n 's/^test/mytest/p' example-----(-n)選項和p標誌一起使用表示只打印那些發生替換的行。也就是說,如果某一行開頭的test被替換成mytest,就打印它。
  •      $ sed 's/^192.168.0.1/&localhost/'example-----&符號表示替換換字符串中被找到的部份。所有以192.168.0.1開頭的行都會被替換成它自已加localhost,變成192.168.0.1localhost。
  •      $ sed -n 's/\(love\)able/\1rs/p' example-----love被標記爲1,所有loveable會被替換成lovers,而且替換的行會被打印出來。
  •      $ sed 's#10#100#g' example-----不論什麼字符,緊跟着s命令的都被認爲是新的分隔符,所以,“#”在這裏是分隔符,代替了默認的“/”分隔符。表示把所有10替換成100。


選定行的範圍:逗號

  •      $ sed -n '/test/,/check/p' example-----所有在模板test和check所確定的範圍內的行都被打印。
  •      $ sed -n '5,/^test/p' example-----打印從第五行開始到第一個包含以test開始的行之間的所有行。
  •      $ sed '/test/,/check/s/$/sed test/' example-----對於模板test和west之間的行,每行的末尾用字符串sed test替換。


多點編輯:e命令  

  • $ sed -e '1,5d' -e 's/test/check/'example-----(-e)選項允許在同一行裏執行多條命令。如例子所示,第一條命令刪除1至5行,第二條命令用check替換test。命令的執行順序對結果有影響。如果兩個命令都是替換命令,那麼第一個替換命令將影響第二個替換命令的結果。
  •      $ sed --expression='s/test/check/' --expression='/love/d' example-----一個比-e更好的命令是--expression。它能給sed表達式賦值。


從文件讀入:r命令  

  •      $ sed '/test/r file' example-----file裏的內容被讀進來,顯示在與test匹配的行後面,如果匹配多行,則file的內容將顯示在所有匹配行的下面。


寫入文件:w命令  

  •      $ sed -n '/test/w file' example-----在example中所有包含test的行都被寫入file裏。


追加命令:a命令  

  •      $ sed '/^test/a\\--->this is a example' example<-----'this is a example'被追加到以test開頭的行後面,sed要求命令a後面有一個反斜槓。


插入:i命令 $ sed '/test/i\\
new line
-------------------------' example
如果test被匹配,則把反斜槓後面的文本插入到匹配行的前面。
下一個:n命令  

  •      $ sed '/test/{ n; s/aa/bb/; }' example-----如果test被匹配,則移動到匹配行的下一行,替換這一行的aa,變爲bb,並打印該行,然後繼續。


變形:y命令  

  •      $ sed '1,10y/abcde/ABCDE/' example-----把1--10行內所有abcde轉變爲大寫,注意,正則表達式元字符不能使用這個命令。


退出:q命令  

  •      $ sed '10q' example-----打印完第10行後,退出sed。


保持和獲取:h命令和G命令  

  • $ sed -e '/test/h' -e '$Gexample-----在sed處理文件的時候,每一行都被保存在一個叫模式空間的臨時緩衝區中,除非行被刪除或者輸出被取消,否則所有被處理的行都將打印在屏幕上。接着模式空間被清空,並存入新的一行等待處理。在這個例子裏,匹配test的行被找到後,將存入模式空間,h命令將其複製並存入一個稱爲保持緩存區的特殊緩衝區內。第二條語句的意思是,當到達最後一行後,G命令取出保持緩衝區的行,然後把它放回模式空間中,且追加到現在已經存在於模式空間中的行的末尾。在這個例子中就是追加到最後一行。簡單來說,任何包含test的行都被複制並追加到該文件的末尾。


保持和互換:h命令和x命令  

  •      $ sed -e '/test/h' -e '/check/x' example -----互換模式空間和保持緩衝區的內容。也就是把包含test與check的行互換。


      7. 腳本

Sed腳本是一個sed的命令清單,啓動Sed時以-f選項引導腳本文件名。Sed對於腳本中輸入的命令非常挑剔,在命令的末尾不能有任何空白或文本,如果在一行中有多個命令,要用分號分隔。以#開頭的行爲註釋行,且不能跨行。

     8. 小技巧
  

  •      在sed的命令行中引用shell變量時要使用雙引號,而不是通常所用的單引號。下面是一個根據name變量的內容來刪除named.conf文件中zone段的腳本:
         name='zone\ "localhost"'
    sed "/$name/,/};/d" named.conf


sed -i "s/oldstring/newstring/g" `grep oldstring -rl yourdir`

例如:替換/home下所有文件中的www.itbbs.cn爲chinafar.com

sed -i "s/www.itbbs.cn/chinafar.com/g" `grep www.itbbs.cn -rl /home` 

二、下面這條命令:
perl -pi -e 's|ABCD|Linux|g' `find ./ -type f`
將調用perl執行一條替換命令,把find命令找到的所有文件內容中的ABCD替換爲Linux

find ./ -type f
此命令是顯示當前目錄下所有的文件

上面的“s|ABCD|Linux| g”是perl要執行的腳本,即把所有ABCD替換爲Linux
如果不寫最後的那個g,“s|ABCD|Linux| ”將只替換每一行開頭的ABCD 


當編輯指令(參照[section2.2])在命令列上執行時,其前必須加上選項-e。其命令格式如下:

sed-e'編輯指令1'-e'編輯指令2'...文件檔

其中,所有編輯指令都緊接在選項-e之後,並置於兩個"'"特殊字元間。另外,命令上編輯指令的執行是由

左而右。

一般編輯指令不多時,使用者通常直接在命令上執行它們。

例如,刪除yel.dat內1至10行資料,並將其餘文字中的"yellow"字串改成"black"字串。此時,可將編輯指令直接在命令上執行,其命令如下:

sed-e'1,10d'-e's/yellow/black/g'yel.dat

在命令中,編輯指令'1,10d'(解[5])執行刪除1至10行資料;編輯指令's/yellow/black/g'(解[6]),

"yellow"字串替換(substuite)成"black"字串。

2.2sed的編輯指令

sed編輯指令的格式如下:

[address1[,address2]]function[argument]

其中,位址參數address1、address2爲行數或regularexpression字串,表示所執行編輯的資料行;函數參

數function[argument]爲sed的內定函數,表示執行的編輯動作。

下面兩小節,將仔細介紹位址參數的表示法與有哪些函數參數供選擇。

2.2.1位址(address)參數的表示法

實際上,位址參數表示法只是將要編輯的資料行,用它們的行數或其中的字串來代替表示它們。下面舉幾個例子

說明(指令都以函數參數d(參照[section4.2])爲例):

刪除檔內第10行資料,則指令爲10d。

刪除含有"man"字串的資料行時,則指令爲/man/d。

刪除檔內第10行到第200行資料,則指令爲10,200d。

刪除檔內第10行到含"man"字串的資料行,則指令爲10,/man/d。

接下來,以位址參數的內容與其個數兩點,完整說明指令中位址參數的表示法(同樣也以函數參數d爲例)。

位址參數的內容:

位址爲十進位數字:此數字表示行數。當指令執行時,將對符合此行數的資料執行函數參數指示的編輯動作。例如,

刪除資料檔中的第15行資料,則指令爲15d(參照[section4.2])。其餘類推,如刪除資料檔中的第m行資料,則

指令爲md。

位址爲regularexpression(參照[附錄A]):

當資料行中有符合regularexpression所表示的字串時,則執行函數參數指示的編輯動作。另外,在

regularexpression前後必須加上"/"。例如指令爲/t.*t/d,表示刪除所有含兩"t"字母的資料行。其中,"."

表示任意字元;"*"表示其前字元可重任意次,它們結合".*"表示兩"t"字母間的任意字串。

位址參數的個數:在指令中,當沒有位址參數時,表示全部資料行執行函數參數所指示的編輯動作;當只有一位址

參數時,表示只有符合位址的資料行才編輯;當有兩個位址參數,如address1,address2時,表示對資料區執行

編輯,address1代表起始資料行,address2代表結束資料行。對於上述內容,以下面例子做具說明。

例如指令爲

d

其表示刪除檔內所有資料行。

例如指令爲

5d

其表示刪除檔內第五行資料。

例如指令爲

1,/apple/d

其表示刪除資料區,由檔內第一行至內有"apple"字串的資料行。

例如指令爲

/apple/,/orange/d

其表示刪除資料區,由檔內含有"apple"字串至含有"orange"字串的資料行

2.2.2有那些函數(function)參數

下頁表中介紹所有sed的函數參數(參照[chapter4])的功能。

函數參數功能

:label建立scriptfile內指令互相參考的位置。

 

 

 

#####################################################

http://blog.csdn.net/wujiangguizhen/article/details/12458119

1.創建文件夾
#!/bin/sh
mkdir -m 777 "%%1"

2.創建文件
#!/bin/sh
touch "%%1"

3.刪除文件
#!/bin/sh
rm -if "%%1"

4.刪除文件夾
#!/bin/sh
rm -rf "%%1"

5.刪除一個目錄下所有的文件夾
#!/bin/bash
direc="%%1" #$(pwd)
for dir2del in $direc/* ; do
if [ -d $dir2del ]; then
  rm -rf $dir2del
fi
done

6.清空文件夾
#!/bin/bash
direc="%%1" #$(pwd)
rm -if $direc/*
for dir2del in $direc/* ; do
if [ -d $dir2del ]; then
  rm -rf $dir2del
fi
done

7.讀取文件
#!/bin/sh
7.1.操作系統默認編碼
cat "%%1" | while read line; do
echo $line;
done

7.2.UTF-8編碼
cat "%%1" | while read line; do
echo $line;
done

7.3.分塊讀取
cat "%%1" | while read line; do
echo $line;
done

8.寫入文件
#!/bin/sh
cat > "%%1" << EOF
%%2
EOF

tee "%%1" > /dev/null << EOF
%%2
EOF

#sed -i '$a %%2' %%2

9.寫入隨機文件
#!/bin/sh
cat > "%%1" << EOF
%%2
EOF

tee "%%1" > /dev/null << EOF
%%2
EOF

#sed -i '$a %%2' %%2

10.讀取文件屬性
#!/bin/bash
file=%%1
file=${file:?'必須給出參數'}
if [ ! -e $file ]; then
    echo "$file 不存在"
    exit 1
fi
if [ -d $file ]; then
    echo "$file 是一個目錄"
    if [ -x $file ]; then
        echo "可以"
    else
        echo "不可以"
    fi
    echo "對此進行搜索"  
elif [ -f $file ]; then
    echo "$file 是一個正規文件"
else
    echo "$file不是一個正規文件"
fi
if [ -O $file ]; then
    echo "你是$file的擁有者"
else
    echo "你不是$file的擁有者"
fi
if [ -r $file ]; then
    echo "你對$file擁有"
else
    echo "你並不對$file擁有"
fi
echo "可讀權限"
if [ -w $file ]; then
    echo "你對$file擁有"
else
    echo "你並不對$file擁有"
fi
echo "可寫權限"
if [ -x $file -a ! -d $file ]; then
    echo "你擁有對$file"
else
    echo "你並不擁有對$file"
fi
echo "可執行的權限"

11.寫入文件屬性
#!/bin/bash
#修改存放在ext2、ext3、ext4、xfs、ubifs、reiserfs、jfs等文件系統上的文件或目錄屬性,使用權限超級用戶。
#一些功能是由Linux內核版本來支持的,如果Linux內核版本低於2.2,那麼許多功能不能實現。同樣-D檢查壓縮文件中的錯誤的功能,需要2.5.19以上內核才能支持。另外,通過chattr命令修改屬性能夠提高系統的安全性,但是它並不適合所有的目錄。chattr命令不能保護/、/dev、/tmp、/var目錄。
chattr [-RV] [-+=AacDdijsSu] [-v version] 文件或目錄
  -R:遞歸處理所有的文件及子目錄。
  -V:詳細顯示修改內容,並打印輸出。
  -:失效屬性。
  +:激活屬性。
  = :指定屬性。
  A:Atime,告訴系統不要修改對這個文件的最後訪問時間。
  S:Sync,一旦應用程序對這個文件執行了寫操作,使系統立刻把修改的結果寫到磁盤。
  a:Append Only,系統只允許在這個文件之後追加數據,不允許任何進程覆蓋或截斷這個文件。如果目錄具有這個屬性,系統將只允許在這個目錄下建立和修改文件,而不允許刪除任何文件。
  i:Immutable,系統不允許對這個文件進行任何的修改。如果目錄具有這個屬性,那麼任何的進程只能修改目錄之下的文件,不允許建立和刪除文件。
  D:檢查壓縮文件中的錯誤。
  d:No dump,在進行文件系統備份時,dump程序將忽略這個文件。
  C:Compress,系統以透明的方式壓縮這個文件。從這個文件讀取時,返回的是解壓之後的數據;而向這個文件中寫入數據時,數據首先被壓縮之後才寫入磁盤。
  S:Secure Delete,讓系統在刪除這個文件時,使用0填充文件所在的區域。
  u:Undelete,當一個應用程序請求刪除這個文件,系統會保留其數據塊以便以後能夠恢復刪除這個文件。

12.枚舉一個目錄中的所有文件夾
#!/bin/bash
OLDIFS=$IFS
IFS=:
for path in $( find "%%1" -type d -printf "%p$IFS")
do
#"$path"
done
IFS=$OLDIFS

13.複製文件夾
#!/bin/sh
cp -rf "%%1" "%%2"

14.複製一個目錄下所有的文件夾到另一個目錄下
#!/bin/bash
direc="%%1" #$(pwd)
for dir2cp in $direc/* ; do
if [ -d $dir2cp ]; then
  cp $dir2cp "%%2"
fi
done

15.移動文件夾
#!/bin/sh
mv -rf "%%1" "%%2"

16.移動一個目錄下所有的文件夾到另一個目錄下
#!/bin/bash
direc="%%1" #$(pwd)
for dir2mv in $direc/* ; do
if [ -d $dir2mv ]; then
  mv $dir2mv "%%2"
fi
done

17.以一個文件夾的框架在另一個目錄下創建文件夾和空文件
#!/bin/bash
direc="%%1" #$(pwd)
OLDIFS=$IFS
IFS=:
for path in $( find $direc -type d -printf "%p$IFS")
do
mkdir -p "%%2/${path:${#direc}+1}"
done
IFS=$OLDIFS
#cp -a "%%1" "%%2"

表達式 含義
${#string}
{#string}
1,取得字符串長度
string=abc12342341          //等號二邊不要有空格
echo ${#string}             //結果11
expr length $string         //結果11
expr "$string" : ".*"       //結果11 分號二邊要有空格,這裏的:根match的用法差不多2,字符串所在位置
expr index $string '123'    //結果4 字符串對應的下標是從0開始的這個方法讓我想起來了js的indexOf,各種語言對字符串的操作方法大方向都差不多,如果有語言基礎的話,學習shell會很快的。
3,從字符串開頭到子串的最大長度
expr match $string 'abc.*3' //結果9個人覺得這個函數的用處不大,爲什麼要從開頭開始呢。
4,字符串截取
echo ${string:4}      //2342341  從第4位開始截取後面所有字符串
echo ${string:3:3}    //123      從第3位開始截取後面3位
echo ${string:3:6}    //123423   從第3位開始截取後面6位
echo ${string: -4}    //2341  :右邊有空格   截取後4位
echo ${string:(-4)}   //2341  同上
expr substr $string 3 3   //123  從第3位開始截取後面3位上面的方法讓我想起了,php的substr函數,後面截取的規則是一樣的。
5,匹配顯示內容
//例3中也有match和這裏的match不同,上面顯示的是匹配字符的長度,而下面的是匹配的內容
expr match $string '\([a-c]*[0-9]*\)'  //abc12342341
expr $string : '\([a-c]*[0-9]\)'       //abc1
expr $string : '.*\([0-9][0-9][0-9]\)' //341 顯示括號中匹配的內容這裏括號的用法,是不是根其他的括號用法有相似之處呢,
6,截取不匹配的內容
echo ${string#a*3}     //42341  從$string左邊開始,去掉最短匹配子串
echo ${string#c*3}     //abc12342341  這樣什麼也沒有匹配到
echo ${string#*c1*3}   //42341  從$string左邊開始,去掉最短匹配子串
echo ${string##a*3}    //41     從$string左邊開始,去掉最長匹配子串
echo ${string%3*1}     //abc12342  從$string右邊開始,去掉最短匹配子串
echo ${string%%3*1}    //abc12     從$string右邊開始,去掉最長匹配子串這裏要注意,必須從字符串的第一個字符開始,或者從最後一個開始,
7,匹配並且替換
echo ${string/23/bb}   //abc1bb42341  替換一次
echo ${string//23/bb}  //abc1bb4bb41  雙斜槓替換所有匹配
echo ${string/#abc/bb} //bb12342341   #以什麼開頭來匹配,根php中的^有點像
echo ${string/%41/bb}  //abc123423bb  %以什麼結尾來匹配,根php中的$有點像

#!/bin/bash
direc=$(pwd)
for file in "$(direc)/*"
do
if [ "${file##*.}" = "sh" ]; then
xterm -e bash $file
elif [ "${file##*.}" = "bin" ]; then
xterm -e $file
elif [ "${file##*.}" = "run" ]; then
xterm -e $file
elif [ "${file##*.}" = "bundle" ]; then
xterm -e $file
elif [ "${file##*.}" = "pl" ]; then
xterm -e perl $file
elif [ "${file##*.}" = "class" ]; then
xterm -e java ${file%.*}
elif [ "${file##*.}" = "rpm" ]; then
xterm -e rpm -ivh $file
elif [ "${file##*.}" = "rb" ]; then
xterm -e ruby $file
elif [ "${file##*.}" = "py" ]; then
xterm -e python $file
elif [ "${file##*.}" = "jar" ]; then
xterm -e java -jar $file
fi
done
OLDIFS=$IFS
IFS=:
for path in $( find $direc -type d -printf "%p$IFS")
do
for file in `ls $path`
do
if [ "${file##*.}" = "sh" ]; then
xterm -e bash """"$path"/"$file""""
elif [ "${file##*.}" = "bin" ]; then
xterm -e """"$path"/"$file""""
elif [ "${file##*.}" = "run" ]; then
xterm -e """"$path"/"$file""""
elif [ "${file##*.}" = "bundle" ]; then
xterm -e """"$path"/"$file""""
elif [ "${file##*.}" = "pl" ]; then
xterm -e perl """"$path"/"$file""""
elif [ "${file##*.}" = "class" ]; then
xterm -e java """"$path"/"${file%.*}""""
elif [ "${file##*.}" = "rpm" ]; then
xterm -e rpm -ivh """"$path"/"$file""""
elif [ "${file##*.}" = "rb" ]; then
xterm -e ruby """"$path"/"$file""""
elif [ "${file##*.}" = "py" ]; then
xterm -e python """"$path"/"$file""""
elif [ "${file##*.}" = "jar" ]; then
xterm -e java -jar """"$path"/"$file""""
fi
done
done
IFS=$OLDIFS

18.複製文件
#!/bin/sh
cp %%1 %%2

19.複製一個目錄下所有的文件到另一個目錄
#!/bin/bash
direc="%%1" $(pwd)
for file in "$direc/*"
do
cp "$file" "%%1"
done

20.提取擴展名
#!/bin/sh
%%2=${%%1##.}

21.提取文件名
#!/bin/sh
%%2="$(basename %%1)"

22.提取文件路徑
#!/bin/sh
%%2="$(dirname %%1)"

23.替換擴展名
#!/bin/sh
%%3="$(basename %%1)$%%2"

24.追加路徑
#!/bin/sh
%%3="$(dirname %%1)/$%%2"

25.移動文件
#!/bin/sh
mv "%%1" "%%2"

26.移動一個目錄下所有文件到另一個目錄
#!/bin/bash
direc="%%1" #$(pwd)
OLDIFS=$IFS
IFS=:
for file in "$(direc)/*"
do
mv "$file" "%%1"
done
IFS=$OLDIFS

27.指定目錄下搜索文件
#!/bin/sh
find -name "%%1"

28.打開文件對話框
#!/bin/sh
%%1="$(Xdialog --fselect '~/' 0 0 2>&1)"

29.文件分割
#!/bin/sh
split -b 2k "%%1"

while read f1 f2 f3
do
    echo $f1 >> f1
    echo $f2 >> f2
    echo $f3 >> f3
done


#!/bin/bash
  linenum=`wc   -l   httperr8007.log|   awk   '{print   $1}'`  
  n1=1  
  file=1  
  while   [   $n1   -lt   $linenum   ]  
  do  
                  n2=`expr   $n1   +   999`  
                  sed   -n   "${n1},   ${n2}p"   httperr8007.log >   file_$file.log    
                  n1=`expr   $n2   +   1`  
                  file=`expr   $file   +   1`  
  done  




其中httperr8007.log爲你想分割的大文件,file_$file.log  爲分割後的文件,最後爲file_1.log,file_2.log,file_3.log……,分割完後的每個文件只有1000行(參數可以自己設置)

split 參數:
-b  :後面可接欲分割成的檔案大小,可加單位,例如 b, k, m 等;
-l  :以行數來進行分割;



#按每個文件1000行來分割除

split -l 1000 httperr8007.log httperr

httpaa,httpab,httpac ........

#按照每個文件100K來分割

split -b 100k httperr8007.log http

httpaa,httpab,httpac ........

#!/bin/bash
if [ $# -ne 2 ]; then
echo 'Usage: split file size(in bytes)'
exit
fi

file=$1
size=$2

if [ ! -f $file ]; then
echo "$file doesn't exist"
exit
fi

#TODO: test if $size is a valid integer

filesize=`/bin/ls -l $file | awk '{print $5}'`
echo filesize: $filesize

let pieces=$filesize/$size
let remain=$filesize-$pieces*$size
if [ $remain -gt 0 ]; then
let pieces=$pieces+1
fi
echo pieces: $pieces

i=0
while [ $i -lt $pieces ];
do
echo split: $file.$i:
dd if=$file of=$file.$i bs=$size count=1 skip=$i
let i=$i+1
done

echo "#!/bin/bash" > merge

echo "i=0" >> merge
echo "while [ $i -lt $pieces ];" >> merge
echo "do" >> merge
echo " echo merge: $file.$i" >> merge
echo " if [ ! -f $file.$i ]; then" >> merge
echo " echo merge: $file.$i missed" >> merge
echo " rm -f $file.merged" >> merge
echo " exit" >> merge
echo " fi" >> merge
echo " dd if=$file.$i of=$file.merged bs=$size count=1 seek=$i" >> merge
echo " let i=$i+1" >> merge
echo "done" >> merge
chmod u+x merge'

30.文件合併
#!/bin/sh
cp "%%1"+"%%2" "%%3"

exec 3<f1
exec 4<f2
while read f1 <&3 && read f2 <&4
do
    echo $f1 $f2 >> join.txt
done

#!/bin/bash
if [ $# -ne 2 ]; then
echo 'Usage: split file size(in bytes)'
exit
fi

file=$1
size=$2

if [ ! -f $file ]; then
echo "$file doesn't exist"
exit
fi

#TODO: test if $size is a valid integer

filesize=`/bin/ls -l $file | awk '{print $5}'`
echo filesize: $filesize

let pieces=$filesize/$size
let remain=$filesize-$pieces*$size
if [ $remain -gt 0 ]; then
let pieces=$pieces+1
fi
echo pieces: $pieces

i=0
while [ $i -lt $pieces ];
do
echo split: $file.$i:
dd if=$file of=$file.$i bs=$size count=1 skip=$i
let i=$i+1
done

echo "#!/bin/bash" > merge

echo "i=0" >> merge
echo "while [ $i -lt $pieces ];" >> merge
echo "do" >> merge
echo " echo merge: $file.$i" >> merge
echo " if [ ! -f $file.$i ]; then" >> merge
echo " echo merge: $file.$i missed" >> merge
echo " rm -f $file.merged" >> merge
echo " exit" >> merge
echo " fi" >> merge
echo " dd if=$file.$i of=$file.merged bs=$size count=1 seek=$i" >> merge
echo " let i=$i+1" >> merge
echo "done" >> merge
chmod u+x merge'

31.文件簡單加密
#!/bin/bash
#make test && make strings && sudo make install
shc -r -f %%1.sh
#%%1.x
#%%1.x.c

32.文件簡單解密
#!/bin/bash
#make test && make strings && sudo make install
shc -r -f %%1.sh
#%%1.x
#%%1.x.c

33.讀取ini文件屬性
#!/bin/bash
if [ "$%%3" = "" ];then
   sed -n "/\[$%%2\]/,/\[.*\]/{
   /^\[.*\]/d
   /^[ ]*$/d
   s/;.*$//
   p
   }" $1
elif [ "$%%4" = "" ];then
   sed -n "/\[$%%2\]/,/\[.*\]/{
   /^\[.*\]/d
   /^[ ]*$/d
   s/;.*$//
   s/^[ |        ]*$%%3[ | ]*=[ |   ]*\(.*\)[ |     ]*/\1/p
   }" $1
else
       if [ "$%%4" = "#" ];then
            sed "/\[$%%2\]/,/\[.*\]/{
            s/^[ |        ]*$%%3[ |    ]*=.*/ /
            }p" $1 > /tmp/sed$$
            mv /tmp/sed$$ $1
       else
            sed "/\[$2\]/,/\[.*\]/{
            s/^[ |        ]*$%%3[ |    ]*=.*/$%%3=$%%4/
            }p" $1 > /tmp/sed$$
            mv /tmp/sed$$ $%%1
       fi
fi

34.合併一個文件下所有的文件
#!/bin/sh
cat $(ls |grep -E '%%1\.') > %%1

#!/bin/bash
OLDIFS=$IFS
IFS=:
for path in $( find %%1 -type d -printf "%p$IFS")
do
for file in $path/*.c $path/*.cpp
do
if [[ ! "$file" =~ \*.[A-Za-z]+ ]]; then
#"$(path)/$(file)"
fi
done
done
IFS=$OLDIFS

#!/bin/bash
cat <<'EOF'> combine.c
#include<stdio.h>
int main()
{
FILE *f1,*f2,*f3;
f1=fopen("a1.txt","r");
f2=fopen("a2.txt","r");
f3=fopen("a3.txt","w");
int a,b;
a=getw(f1);   /*從a1.txt和a2.txt中分別取最小的數a和b*/
b=getw(f2);
while(!feof(f1)&&!feof(f2))  /*兩個文件都沒結束時,執行循環、比較*/
{
if(a<=b)
{
putw(a,f3);
a=getw(f1);
}
else
{putw(b,f3);
b=getw(f2);
}
   }
if(feof(f1))  /*文件a1.txt結束時,把a2.txt中的數全部輸入a3.txt*/
{putw(b,f3);
while((b=getw(f2))!=EOF)
putw(b,f3);
}
if(feof(f2))   /*同上*/
{
putw(a,f3);
while((a=getw(f1))!=EOF)
putw(a,f3);
}
fclose(f1);
fclose(f2);
fclose(f3);
printf("已完成!");
return 0;
}
EOF
gcc -o combine combine.c
if [ $? -eq 0 ]; then
./combine
else
echo 'Compile ERROR'
fi

35.寫入ini文件屬性
#!/bin/bash
if [ "$%%3" = "" ];then
   sed -n "/\[$%%2\]/,/\[.*\]/{
   /^\[.*\]/d
   /^[ ]*$/d
   s/;.*$//
   p
   }" $1
elif [ "$%%4" = "" ];then
   sed -n "/\[$%%2\]/,/\[.*\]/{
   /^\[.*\]/d
   /^[ ]*$/d
   s/;.*$//
   s/^[ |        ]*$%%3[ | ]*=[ |   ]*\(.*\)[ |     ]*/\1/p
   }" $1
else
       if [ "$%%4" = "#" ];then
            sed "/\[$%%2\]/,/\[.*\]/{
            s/^[ |        ]*$%%3[ |    ]*=.*/ /
            }p" $1 > /tmp/sed$$
            mv /tmp/sed$$ $%%1
       else
            sed "/\[$%%2\]/,/\[.*\]/{
            s/^[ |        ]*$%%3[ |    ]*=.*/$%%3=$%%4/
            }p" $1 > /tmp/sed$$
            mv /tmp/sed$$ $%%1
       fi
fi

36.獲得當前路徑
#!/bin/sh
%%1=$(pwd)

37.讀取XML數據庫

如何通過shell命令行讀取xml文件中某個屬性所對應的值?
例如:
<key>BuildVersion</key> <string>5</string>
我希望能夠通過Unix shell命令對屬性鍵的名稱BuildVersion進行查詢,返回的結果是5,如何實現呀?
#!/bin/bash
grep BuildVersion|sed 's/.*<.*>\([^<].*\)<.*>.*/\1/'

結果返回的是“BuildVersion”,而不是“5”,如果要查詢BuildVersion自動返回數值5應當如何寫?

應該沒錯的。試一下: echo "<key>BuildVersion</key> <string>5</string>"|grep BuildVersion|sed 's/.*<.*>\([^<].*\)<.*>.*/\1/'我在SL的終端裏試,返回值是5

目前需要從xml文件提取數據,想做一個xmlparser.sh
xml 類似這樣
<result>
   <shareinfo hostip="192.168.0.1" sharename="abcd" password="abc123"></shareinfo>
</result>


希望輸入 xmlparser.sh a.xml hostip可以返回192.168.0.1


#!/bin/sh

if [ $# -ne 2 ];then
   echo "Usage: $0 <xmlfile> <key>"
   exit 0
fi

grep $2 $1|awk '{print $2}'|grep -o "[0-9.]*"



grep $2 $1|awk '{print $2}'|grep -o "[0-9.]*"
改成
grep $2 $1|awk '{print $2}'|grep -Eo "[0-9.]+"
樓上這個有問題,如果我要得到的是
<result>
   <shareinfo hostip="192.168.0.1" sharename="abcd" password="abc123"></shareinfo>
</result>
中的sharename,那麼,呵呵,就錯了

我覺得應該先定位到第二個參數“$2”的位置,然後再提取“=”後面的內容

這裏有個完整的實現:
Parse Simple XML Files using Bash – Extract Name Value Pairs and Attributes
http://www.humbug.in/2010/parse-simple-xml-files-using-bash-extract-name-value-pairs-and-attributes/


不過需要安裝xmllint.

設計到對多個xml文件進行element的讀取和列表。有人做過麼?
舉個例子,
多個xml文件裏面都有
<article>
        <title>xxx</titlel>
</article>

通過shell讀取,然後合併到一起,再生成一個新的xml,但是其他元素不變。
<article>
        <title>aaa</titlel>
</article>
<article>
        <title>bbb</titlel>
</article>

如果格式異常簡單,沒有特例,那麼可以用shell實現
如果有可能格式複雜,因爲shell的命令所使用的正則表達式都不支持跨行匹配,所以用shell來解決這個問題就繞圈子了。
用perl來作這個工作最直接、簡單。perl的XML:DOM模塊是專門處理XML文件的。

偶倒是覺得,用PHP寫Scripts也很方便,功能強大,而且,跨平臺,

#!/bin/sh



sed -n '/<article>/{

N;

/\n[[:space:]]*<title>/{

    N;

    /<article>.*<\/article>/p

    }

D;

n

}'


這小段代碼能把一個xml文件中,你要的東西拿出來.
你可以用for file in $*把這些信息都>>tmpfile中.
然後用sed 在指定文件的指定位置用r命令把tmpfile粘貼進來~~~~

大思路如此^_^  我想有這個東西(只要能正確的跑出結果)後面就不難了吧...

Name
xmllint — command line XML tool

Synopsis
xmllint [[--version] | [--debug] | [--shell] | [--debugent] | [--copy] | [--recover] | [--noent] | [--noout] | [--nonet] | [--htmlout] | [--nowrap] | [--valid] | [--postvalid] | [--dtdvalid URL] | [--dtdvalidfpi FPI] | [--timing] | [--output file] | [--repeat] | [--insert] | [--compress] | [--html] | [--xmlout] | [--push] | [--memory] | [--maxmem nbbytes] | [--nowarning] | [--noblanks] | [--nocdata] | [--format] | [--encode encoding] | [--dropdtd] | [--nsclean] | [--testIO] | [--catalogs] | [--nocatalogs] | [--auto] | [--xinclude] | [--noxincludenode] | [--loaddtd] | [--dtdattr] | [--stream] | [--walker] | [--pattern patternvalue] | [--chkregister] | [--relaxng] | [--schema] | [--c14n]] [xmlfile]

Introduction
The xmllint program parses one or more XML files, specified on the command line as xmlfile. It prints various types of output, depending upon the options selected. It is useful for detecting errors both in XML code and in the XML parser itself.

It is included in libxml2.

Options
--version
Display the version of libxml2 used.
--debug
Parse a file and output an annotated tree of the in-memory version of the document.
--shell
Run a navigating shell. Details on available commands in shell mode are below.
--debugent
Debug the entities defined in the document.
--copy
Test the internal copy implementation.
--recover
Output any parsable portions of an invalid document.
--noent
Substitute entity values for entity references. By default, xmllint leaves entity references in place.
--nocdata
Substitute CDATA section by equivalent text nodes.
--nsclean
Remove redundant namespace declarations.
--noout
Suppress output. By default, xmllint outputs the result tree.
--htmlout
Output results as an HTML file. This causes xmllint to output the necessary HTML tags surrounding the result tree output so the results can be displayed in a browser.
--nowrap
Do not output HTML doc wrapper.
--valid
Determine if the document is a valid instance of the included Document Type Definition (DTD). A DTD to be validated against also can be specified at the command line using the --dtdvalid option. By default, xmllint also checks to determine if the document is well-formed.
--postvalid
Validate after parsing is completed.
--dtdvalid URL
Use the DTD specified by URL for validation.
--dtdvalidfpi FPI
Use the DTD specified by the Public Identifier FPI for validation, note that this will require a Catalog exporting that Public Identifier to work.
--timing
Output information about the time it takes xmllint to perform the various steps.
--output file
Define a file path where xmllint will save the result of parsing. Usually the programs build a tree and save it on stdout, with this option the result XML instance will be saved onto a file.
--repeat
Repeat 100 times, for timing or profiling.
--insert
Test for valid insertions.
--compress
Turn on gzip compression of output.
--html
Use the HTML parser.
--xmlout
Used in conjunction with --html. Usually when HTML is parsed the document is saved with the HTML serializer, but with this option the resulting document is saved with the XML serializer. This is primarily used to generate XHTML from HTML input.
--push
Use the push mode of the parser.
--memory
Parse from memory.
--maxmem nnbytes
Test the parser memory support. nnbytes is the maximum number of bytes the library is allowed to allocate. This can also be used to make sure batch processing of XML files will not exhaust the virtual memory of the server running them.
--nowarning
Do not emit warnings from the parser and/or validator.
--noblanks
Drop ignorable blank spaces.
--format
Reformat and reindent the output. The $XMLLINT_INDENT environment variable controls the indentation (default value is two spaces " ").
--testIO
Test user input/output support.
--encode encoding
Output in the given encoding.
--catalogs
Use the catalogs from $SGML_CATALOG_FILES. Otherwise /etc/xml/catalog is used by default.
--nocatalogs
Do not use any catalogs.
--auto
Generate a small document for testing purposes.
--xinclude
Do XInclude processing.
--noxincludenode
Do XInclude processing but do not generate XInclude start and end nodes.
--loaddtd
Fetch external DTD.
--dtdattr
Fetch external DTD and populate the tree with inherited attributes.
--dropdtd
Remove DTD from output.
--stream
Use streaming API - useful when used in combination with --relaxng or --valid options for validation of files that are too large to be held in memory.
--walker
Test the walker module, which is a reader interface but for a document tree, instead of using the reader API on an unparsed document it works on a existing in-memory tree. Used in debugging.
--chkregister
Turn on node registration. Useful for developers testing libxml2 node tracking code.
--pattern patternvalue
Used to exercise the pattern recognition engine, which can be used with the reader interface to the parser. It allows to select some nodes in the document based on an XPath (subset) expression. Used for debugging.
--relaxng schema
Use RelaxNG file named schema for validation.
--schema schema
Use a W3C XML Schema file named schema for validation.
--c14n
Use the W3C XML Canonicalisation (C14N) to serialize the result of parsing to stdout. It keeps comments in the result.
Shell
xmllint offers an interactive shell mode invoked with the --shell command. Available commands in shell mode include:

base
display XML base of the node
bye
leave shell
cat node
Display node if given or current node.
cd path
Change the current node to path (if given and unique) or root if no argument given.
dir path
Dumps information about the node (namespace, attributes, content).
du path
Show the structure of the subtree under path or the current node.
exit
Leave the shell.
help
Show this help.
free
Display memory usage.
load name
Load a new document with the given name.
ls path
List contents of path (if given) or the current directory.
pwd
Display the path to the current node.
quit
Leave the shell.
save name
Saves the current document to name if given or to the original name.
validate
Check the document for error.
write name
Write the current node to the given filename.
Catalogs
Catalog behavior can be changed by redirecting queries to the user's own set of catalogs. This can be done by setting the XML_CATALOG_FILES environment variable to a list of catalogs. An empty one should deactivate loading the default /etc/xml/catalog default catalog.

Debugging Catalogs
Setting the environment variable XML_DEBUG_CATALOG using the command "export XML_DEBUG_CATALOG=" outputs debugging information related to catalog operations.

Error Return Codes
On the completion of execution, Xmllint returns the following error codes:

0
No error
1
Unclassified
2
Error in DTD
3
Validation error
4
Validation error
5
Error in schema compilation
6
Error writing output
7
Error in pattern (generated when [--pattern] option is used)
8
Error in Reader registration (generated when [--chkregister] option is used)
9
Out of memory error

Parse Simple XML Files using Bash – Extract Name Value Pairs and Attributes


2 Comments
1
Tweet




Pratik Sinha | July 31, 2010


I have written up a simple routine par***ML to parse simple XML files to extract unique name values pairs and their attributes. The script extracts all xml tags of the format <abc arg1="hello">xyz</abc> and dynamically creates bash variables which hold values of the attributes as well as the elements. This is a good solution, if you don’t wish to use xpath for some simple xml files. However you will need xmllint installed on your system to use the script. Here’s a sample script which uses the par***ML function
#!/bin/bash
xmlFile=$1

function par***ML() {
  elemList=( $(cat $xmlFile | tr '\n' ' ' | XMLLINT_INDENT="" xmllint --format - | /bin/grep -e "</.*>$" | while read line; do \
    echo $line | sed -e 's/^.*<\///' | cut -d '>' -f 1; \
  done) )

  totalNoOfTags=${#elemList[@]}; ((totalNoOfTags--))
  suffix=$(echo ${elemList[$totalNoOfTags]} | tr -d '</>')
  suffix="${suffix}_"

  for (( i = 0 ; i < ${#elemList[@]} ; i++ )); do
    elem=${elemList[$i]}
    elemLine=$(cat $xmlFile | tr '\n' ' ' | XMLLINT_INDENT="" xmllint --format - | /bin/grep "</$elem>")
    echo $elemLine | grep -e "^</[^ ]*>$" 1>/dev/null 2>&1
    if [ "0" = "$?" ]; then
      continue
    fi
    elemVal=$(echo $elemLine | tr '\011' '\040'| sed -e 's/^[ ]*//' -e 's/^<.*>\([^<].*\)<.*>$/\1/' | sed -e 's/^[ ]*//' | sed -e 's/[ ]*$//')
    xmlElem="${suffix}$(echo $elem | sed 's/-/_/g')"
    eval ${xmlElem}=`echo -ne \""${elemVal}"\"`
    attrList=($(cat $xmlFile | tr '\n' ' ' | XMLLINT_INDENT="" xmllint --format - | /bin/grep "</$elem>" | tr '\011' '\040' | sed -e 's/^[ ]*//' | cut -d '>' -f 1  | sed -e 's/^<[^ ]*//' | tr "'" '"' | tr '"' '\n'  | tr '=' '\n' | sed -e 's/^[ ]*//' | sed '/^$/d' | tr '\011' '\040' | tr ' ' '>'))
    for (( j = 0 ; j < ${#attrList[@]} ; j++ )); do
      attr=${attrList[$j]}
      ((j++))
      attrVal=$(echo ${attrList[$j]} | tr '>' ' ')
      attrName=`echo -ne ${xmlElem}_${attr}`
      eval ${attrName}=`echo -ne \""${attrVal}"\"`
    done
  done
}

par***ML
echo "$status_xyz |  $status_abc |  $status_pqr" #Variables for each  XML ELement
echo "$status_xyz_arg1 |  $status_abc_arg2 |  $status_pqr_arg3 | $status_pqr_arg4" #Variables for each XML Attribute
echo ""

#All the variables that were produced by the par***ML function
set | /bin/grep -e "^$suffix"

The XML File used for the above script example is:
<?xml version="1.0"?>
<status>
  <xyz arg1="1"> a </xyz>
  <abc arg2="2"> p </abc>
  <pqr arg3="3" arg4="a phrase"> x </pqr>
</status>


The root tag, which in this case is “status”, is used as a suffix for all variables. Once the XML file is passed to the function, it dynamically creates the variables $status_xyz, $status_abc, $status_pqr, $status_xyz_arg1, $status_abc_arg2, $status_pqr_arg3 and $status_pqr_arg4.

The output when the script is ran with the xml file as an argument is
@$ bash  par***ML.sh test.xml
a |  p |  x
1 |  2 |  3 | a phrase

status_abc=p
status_abc_arg2=2
status_pqr=x
status_pqr_arg3=3
status_pqr_arg4='a phrase'
status_xyz=a
status_xyz_arg1=1

This script won’t work for XML files like the one below with duplicate element names.
<?xml version="1.0"?>
<status>
  <test arg1="1"> a </test>
  <test arg2="2"> p </test>
  <test arg3="3" arg4="a phrase"> x </test>
</status>


This script also won’t be able to extract attributes of elements without any CDATA. For eg, the script won’t be able to create variables corresponding to <test arg1="1">. It will only create the variables corresponding to <test1 arg2="2">abc</test1>.
<?xml version="1.0"?>
<status>
  <test arg1="1">
    <test1 arg2="2">abc</test1>
  </test>
</status>

38.寫入XML數據庫
#!/bin/bash

39.ZIP壓縮文件
#!/bin/sh
zip -r "/%%1" "%%2"

40.ZIP解壓縮
#!/bin/sh
unzip -x "/%%1" "%%2"

41.獲得應用程序完整路徑
#!/bin/bash

42.ZIP壓縮文件夾
#!/bin/bash

43.遞歸刪除目錄下的文件
#!/bin/bash
rm -if "%%1/*"
OLDIFS=$IFS
IFS=:
for path in $( find %%1 -type d -printf "%p$IFS")
do
for file in $path/*.c $path/*.cpp
do
if [[ ! "$file" =~ \*.[A-Za-z]+ ]]; then
#"$(path)/$(file)"
fi
done
done
IFS=$OLDIFS

44.IDEA加密算法
#!/bin/bash

45.RC6算法
#!/bin/bash
cat <<'EOF'> rc6.c
#include<stdio.h>
/* Timing data for RC6 (rc6.c)

128 bit key:
Key Setup:    1632 cycles
Encrypt:       270 cycles =    94.8 mbits/sec
Decrypt:       226 cycles =   113.3 mbits/sec
Mean:          248 cycles =   103.2 mbits/sec

192 bit key:
Key Setup:    1885 cycles
Encrypt:       267 cycles =    95.9 mbits/sec
Decrypt:       235 cycles =   108.9 mbits/sec
Mean:          251 cycles =   102.0 mbits/sec

256 bit key:
Key Setup:    1877 cycles
Encrypt:       270 cycles =    94.8 mbits/sec
Decrypt:       227 cycles =   112.8 mbits/sec
Mean:          249 cycles =   103.0 mbits/sec

*/

#include "../std_defs.h"

static char *alg_name[] = { "rc6", "rc6.c", "rc6" };

char **cipher_name()
{
    return alg_name;
}

#define f_rnd(i,a,b,c,d)                    \
        u = rotl(d * (d + d + 1), 5);       \
        t = rotl(b * (b + b + 1), 5);       \
        a = rotl(a ^ t, u) + l_key;      \
        c = rotl(c ^ u, t) + l_key[i + 1]

#define i_rnd(i,a,b,c,d)                    \
        u = rotl(d * (d + d + 1), 5);       \
        t = rotl(b * (b + b + 1), 5);       \
        c = rotr(c - l_key[i + 1], t) ^ u;  \
        a = rotr(a - l_key, u) ^ t

u4byte  l_key[44];  /* storage for the key schedule         */

/* initialise the key schedule from the user supplied key   */

u4byte *set_key(const u4byte in_key[], const u4byte key_len)
{   u4byte  i, j, k, a, b, l[8], t;

    l_key[0] = 0xb7e15163;

    for(k = 1; k < 44; ++k)
       
        l_key[k] = l_key[k - 1] + 0x9e3779b9;

    for(k = 0; k < key_len / 32; ++k)

        l[k] = in_key[k];

    t = (key_len / 32) - 1; // t = (key_len / 32);

    a = b = i = j = 0;

    for(k = 0; k < 132; ++k)
    {   a = rotl(l_key + a + b, 3); b += a;
        b = rotl(l[j] + b, b);
        l_key = a; l[j] = b;
        i = (i == 43 ? 0 : i + 1); // i = (i + 1) % 44; 
        j = (j == t ? 0 : j + 1);  // j = (j + 1) % t;
    }

    return l_key;
};

/* encrypt a block of text  */

void encrypt(const u4byte in_blk[4], u4byte out_blk[4])
{   u4byte  a,b,c,d,t,u;

    a = in_blk[0]; b = in_blk[1] + l_key[0];
    c = in_blk[2]; d = in_blk[3] + l_key[1];

    f_rnd( 2,a,b,c,d); f_rnd( 4,b,c,d,a);
    f_rnd( 6,c,d,a,b); f_rnd( 8,d,a,b,c);
    f_rnd(10,a,b,c,d); f_rnd(12,b,c,d,a);
    f_rnd(14,c,d,a,b); f_rnd(16,d,a,b,c);
    f_rnd(18,a,b,c,d); f_rnd(20,b,c,d,a);
    f_rnd(22,c,d,a,b); f_rnd(24,d,a,b,c);
    f_rnd(26,a,b,c,d); f_rnd(28,b,c,d,a);
    f_rnd(30,c,d,a,b); f_rnd(32,d,a,b,c);
    f_rnd(34,a,b,c,d); f_rnd(36,b,c,d,a);
    f_rnd(38,c,d,a,b); f_rnd(40,d,a,b,c);

    out_blk[0] = a + l_key[42]; out_blk[1] = b;
    out_blk[2] = c + l_key[43]; out_blk[3] = d;
};

/* decrypt a block of text  */

void decrypt(const u4byte in_blk[4], u4byte out_blk[4])
{   u4byte  a,b,c,d,t,u;

    d = in_blk[3]; c = in_blk[2] - l_key[43];
    b = in_blk[1]; a = in_blk[0] - l_key[42];

    i_rnd(40,d,a,b,c); i_rnd(38,c,d,a,b);
    i_rnd(36,b,c,d,a); i_rnd(34,a,b,c,d);
    i_rnd(32,d,a,b,c); i_rnd(30,c,d,a,b);
    i_rnd(28,b,c,d,a); i_rnd(26,a,b,c,d);
    i_rnd(24,d,a,b,c); i_rnd(22,c,d,a,b);
    i_rnd(20,b,c,d,a); i_rnd(18,a,b,c,d);
    i_rnd(16,d,a,b,c); i_rnd(14,c,d,a,b);
    i_rnd(12,b,c,d,a); i_rnd(10,a,b,c,d);
    i_rnd( 8,d,a,b,c); i_rnd( 6,c,d,a,b);
    i_rnd( 4,b,c,d,a); i_rnd( 2,a,b,c,d);

    out_blk[3] = d - l_key[1]; out_blk[2] = c;
    out_blk[1] = b - l_key[0]; out_blk[0] = a;
};
int main()
{

return 0;
}
EOF
gcc -o rc6 rc6.c
if [ $? -eq 0 ]; then
./combine
else
echo 'Compile ERROR'
fi

46.Grep
#!/bin/bash
grep -qE %%1 %%2

47.直接創建多級目錄
#!/bin/bash
mkdir -p %%1

48.批量重命名
#!/bin/bash
find $PWD -type f -name '*\.cpp' |sed s/'\.cpp'//g|awk '{MV = "mv"};{C = "\.c"};{ CPP="\.cpp"}; {print MV, $1 CPP , $1 C}'|sh
ls | awk -F '-' '{print "mv "$0" "$2}' #去掉帶'-'的前綴

49.文本查找替換
#!/bin/bash
sed -e 's:%%2:%%3:g' %%1
#sed -e 's/%%2/%%3/g' %%1

50.文件關聯
#!/bin/bash

51.批量轉換編碼從GB2312到Unicode
#!/bin/bash
scode="gbk"
dcode="ucs2"
for FILE in $(find $(pwd) -type f)
do
TMP_file=$(mktemp -p $(pwd))
if [ -f $FILE ]; then
Fright=$(stat -c %a $FILE)
Fuser=$(stat -c %U $FILE)
Fgrp=$(stat -c %G $FILE)
iconv -f $scode -t $dcode $FILE -o $TMP_file
mv $TMP_file $FILE
chmod $Fright $FILE
chown $Fuser.$Fgrp $FILE
fi
done

52.設置JDK環境變量
#!/bin/bash
find "$PWD" -type f \( -iname '*.bin' \) -print0 | xargs -0 chmod +x
find -type f \( -iname '*.bin' \) -print |
while read filename
do
    case "$filename" in
    *.bin)
        xterm -e "$filename" && rm -if "$filename"
        ;;
    esac
done
OLDIFS=$IFS
IFS=$'\n'
for line in `cat ~/.bashrc`
do
if [[ "$line" =~ .*export.* ]]; then
    if [[ "$line" =~ .*JAVA_HOME=.* ]]; then
      if [[ "$line" =~ =(\/([0-9a-zA-Z._]+))+ ]]; then
       javahome=$line
      fi
    fi
fi
if [[ "$line" =~ export\ PATH=\$PATH:\$JAVA_HOME/bin:\$JAVA_HOME/jre/bin$ ]];then
    javapath=$line
fi
if [[ "$line" =~ export\ CLASSPATH=.:\$JAVA_HOME/lib:\$JAVA_HOME/jre/lib$ ]];then
    classpath=$line
fi
done
if [ ! -n "$javahome" ]; then
sed -i '$a export JAVA_HOME='$(pwd)'/jdk1.6.0_25' ~/.bashrc
else
sed -i 's:'${javahome//\\/\\\\}':export JAVA_HOME='$(pwd)'/jdk1.6.0_32:g' ~/.bashrc
fi
if [ ! -n "$javapath" ]; then
sed -i '$a export PATH=$PATH:$JAVA_HOME/bin:$JAVA_HOME/jre/bin' ~/.bashrc
fi
if [ ! -n "$classpath" ]; then
sed -i '$a export CLASSPATH=.:$JAVA_HOME/lib:$JAVA_HOME/jre/lib' ~/.bashrc
fi
IFS=$OLDIFS

#!/bin/bash
shift
OLDIFS=$IFS
IFS=$'\n'
for line in `cat ~/TestBash.txt` #~/.bashrc
do
  if [[ "$line" =~ .*export.* ]]; then
    if [[ "$line" =~ export\ CLASSPATH=.:\$JAVA_HOME/lib:\$JAVA_HOME/jre/lib$ ]]; then
      classpath=$line
    elif [[ "$line" =~ export\ PATH=\$PATH:\$CATALINA_HOME/bin$ ]]; then
      jbosspath=$line
fi
    if [[ "$line" =~ .*JAVA_HOME=.* ]]; then
      if [[ "$line" =~ =(\/([0-9a-zA-Z._]+))+ ]];then
       javahome=$line
      fi
    elif [[ "$line" =~ .*CATALINA_HOME=.* ]];then
      if [[ "$line" =~ =(\/([0-9a-zA-Z._]+))+ ]];then
       catalinahome=$line
      fi
    elif [[ "$line" =~ .*TOMCAT_HOME=.* ]];then
      if [[ "$line" =~ =(\/([0-9a-zA-Z._]+))+ ]];then
       tomcathome=$line
      fi
    elif [[ "$line" =~ .*CATALINA_BASE=.* ]];then
      if [[ "$line" =~ =(\/([0-9a-zA-Z._]+))+ ]];then
       catalinabase=$line
      fi
    elif [[ "$line" =~ .*JBOSS_HOME=.* ]];then
      if [[ "$line" =~ =(\/([0-9a-zA-Z._]+))+ ]];then
       jbosshome=$line
      fi
    fi
  elif [[ "$line" =~ ^PATH=\$PATH:\$JAVA_HOME/bin:\$JAVA_HOME/jre/bin$ ]];then
    javapath=$line
  fi
  if [[ "$line" =~ export\ CLASSPATH=.:\$JAVA_HOME/lib:\$JAVA_HOME/jre/lib$ ]];then
    classpath=$line
  fi
  if [[ "$line" =~ export\ PATH=\$PATH:\$JBOSS_HOME/bin$ ]];then
    jbosspath=$line
  fi
done
if [ ! -n "$javahome" ]; then
sed -i '$a export JAVA_HOME='$(pwd)'/jdk1.6.0_24' ~/TestBash.txt #~/.bashrc
else
sed -i 's:'${javahome//\\/\\\\}':export JAVA_HOME='$(pwd)'/jdk1.6.0_24:g' ~/TestBash.txt
fi
if [ ! -n "$javapath" ]; then
sed -i '$a PATH=$PATH:$JAVA_HOME/bin:$JAVA_HOME/jre/bin' ~/TestBash.txt #~/.bashrc
fi
if [ ! -n "$classpath" ]; then
sed -i '$a export CLASSPATH=.:$JAVA_HOME/lib:$JAVA_HOME/jre/lib' ~/TestBash.txt #~/.bashrc
fi
if [ ! -n "$catalinahome" ]; then
sed -i '$a export CATALINA_HOME='$(pwd) ~/TestBash.txt #~/.bashrc
else
sed -i 's:'${catalinahome//\\/\\\\}':export CATALINA_HOME='$(pwd)':g' ~/TestBash.txt
fi
if [ ! -n "$tomcathome" ]; then
sed -i '$a export TOMCAT_HOME='$(pwd) ~/TestBash.txt #~/.bashrc
else
sed -i 's:'${tomcathome//\\/\\\\}':export TOMCAT_HOME='$(pwd)':g' ~/TestBash.txt
fi
if [ ! -n "$catalinabase" ]; then
sed -i '$a export CATALINA_BASE='$(pwd) ~/TestBash.txt #~/.bashrc
else
sed -i 's:'${catalinabase//\\/\\\\}':export CATALINA_BASE='$(pwd)':g' ~/TestBash.txt
fi
if [ ! -n "$jbosshome" ]; then
sed -i '$a export JBOSS_HOME='$(pwd) ~/TestBash.txt #~/.bashrc
else
sed -i 's:'${jbosshome//\\/\\\\}':export JBOSS_HOME='$(pwd)':g' ~/TestBash.txt
fi
if [ ! -n "$jbosspath" ]; then
sed -i '$a export PATH=$PATH:$CATALINA_HOME/bin' ~/TestBash.txt #~/.bashrc
fi
IFS=$OLDIFS

53.批量轉換編碼從Unicode到GB2312
#!/bin/bash
scode="ucs2"
dcode="gbk"
for FILE in $(find $(pwd) -type f)
do
TMP_file=$(mktemp -p $(pwd))
if [ -f $FILE ]; then
Fright=$(stat -c %a $FILE)
Fuser=$(stat -c %U $FILE)
Fgrp=$(stat -c %G $FILE)
iconv -f $scode -t $dcode $FILE -o $TMP_file
mv $TMP_file $FILE
chmod $Fright $FILE
chown $Fuser.$Fgrp $FILE
fi
done

54.刪除空文件夾
#!/bin/bash
rmdir -p %%1

55.GB2312文件轉UTF-8格式
#!/bin/bash
iconv -f gbk -t utf8 %%1 -o %%2

56.UTF-8文件轉GB2312格式
#!/bin/bash
iconv -f utf8 -t  gbk %%1 -o %%2

57.獲取文件路徑的父路徑
#!/bin/bash
%%1=basename $PWD

58.Unicode文件轉UTF-8格式
#!/bin/bash
iconv -f ucs2 -t  utf-8 %%1 -o %%2

59.CRC循環冗餘校驗
#!/bin/bash
cat <<'EOF'> crc.c
#include<stdio.h>

unsigned long int crc32_table[256]; 

unsigned long int ulPolynomial = 0x04c11db7; 

unsigned long int Reflect(unsigned long int ref, char ch) 

  {     unsigned long int value(0); 

        // 交換bit0和bit7,bit1和bit6,類推 

        for(int i = 1; i < (ch + 1); i++) 

         {            if(ref & 1) 

                      value |= 1 << (ch - i); 

                   ref >>= 1;      } 

        return value; 



init_crc32_table() 

  {     unsigned long int crc,temp; 

        // 256個值 

        for(int i = 0; i <= 0xFF; i++) 

         {   temp=Reflect(i, 8); 

               crc32_table[i]= temp<< 24; 

                for (int j = 0; j < 8; j++){ 

             unsigned long int t1,t2; 

  unsigned long int flag=crc32_table[i]&0x80000000; 

                t1=(crc32_table[i] << 1); 

                if(flag==0) 

                  t2=0; 

                else 

                  t2=ulPolynomial; 

                crc32_table[i] =t1^t2 ;        } 

               crc=crc32_table[i]; 

               crc32_table[i] = Reflect(crc32_table[i], 32); 
        }
}
unsigned long GenerateCRC32(char xdata * DataBuf,unsigned long  len) 

  { 

        unsigned long oldcrc32; 

        unsigned long crc32; 

        unsigned long oldcrc; 

        unsigned  int charcnt; 

         char c,t; 

        oldcrc32 = 0x00000000; //初值爲0 

     charcnt=0; 

         while (len--) { 

                 t= (oldcrc32 >> 24) & 0xFF;   //要移出的字節的值 

     oldcrc=crc_32_tab[t];         //根據移出的字節的值查表 

                 c=DataBuf[charcnt];          //新移進來的字節值 

                 oldcrc32= (oldcrc32 << 8) | c;   //將新移進來的字節值添在寄存器末字節中 

                 oldcrc32=oldcrc32^oldcrc;     //將寄存器與查出的值進行xor運算 

                 charcnt++; 

        } 

         crc32=oldcrc32; 

         return crc32; 



參數表可以先在PC機上算出來,也可在程序初始化時完成。下面是用於計算參數表的c語言子程序,在Visual C++ 6.0下編譯通過。 

#include <stdio.h> 

unsigned long int crc32_table[256]; 

unsigned long int ulPolynomial = 0x04c11db7; 

unsigned long int Reflect(unsigned long int ref, char ch) 

  {     unsigned long int value(0); 

        // 交換bit0和bit7,bit1和bit6,類推 

        for(int i = 1; i < (ch + 1); i++) 

         {            if(ref & 1) 

                      value |= 1 << (ch - i); 

                   ref >>= 1;      } 

        return value; 

}
int main()
{
     unsigned long int crc,temp; 

        // 256個值 

        for(int i = 0; i <= 0xFF; i++) 

         {
temp=Reflect(i, 8);
               crc32_table[i]= temp<< 24; 

                for (int j = 0; j < 8; j++){ 

             unsigned long int t1,t2; 

  unsigned long int flag=crc32_table[i]&0x80000000;
                t1=(crc32_table[i] << 1); 

                if(flag==0) 

                  t2=0; 

                else 

                  t2=ulPolynomial; 

                crc32_table[i] =t1^t2 ;       


               crc=crc32_table[i];
               crc32_table[i] = Reflect(crc32_table[i], 32);
        }
return 0;
}
EOF
gcc -o crc crc.c
if [ $? -eq 0 ]; then
./combine
else
echo 'Compile ERROR'
fi

60.判斷是否爲空文件
#!/bin/bash

61.終止程序
#!/bin/sh
kill -KILL pidof %%1 -s
#killall %%1

62.定時關機
#!/bin/sh
shutdown -h %%1 & #23:00
#shutdown -h now
#halt
#/sbin/poweroff
#init 0

63.顯示進程列表
#!/bin/sh
ps aux
#fuser -l

64.遍歷文件夾列出文件大小
#!/bin/sh
du -sH "%%1/*"

65.GOST算法
#!/bin/bash

66.對目標壓縮文件解壓縮到指定文件夾
#!/bin/bash

67.保存文件時重名自動生成新文件
#!/bin/bash

68.打開網頁
#!/bin/sh
lynx %%1

69.刪除空文件夾整合操作
#!/bin/bash

70.獲取磁盤所有分區
#!/bin/sh
df -k

71.激活一個程序或程序關聯的文件
#!/bin/bash

72.MP3播放
#!/bin/sh
amp "%%1"

73.WAV播放
#!/bin/sh
amp "%%1"

74.寫圖像到剪切板
#!/bin/bash

75.從剪貼板複製圖像到窗體
#!/bin/bash

76.刪除文件夾下的所有文件且不刪除文件夾下的文件夾
#!/bin/sh
rm -if "%%1/*"

77.XML遍歷結點屬性值
#!/bin/bash

78.Unicode文件轉GB2312格式
#!/bin/sh
iconv -f ucs2 -t  gbk %%1 -o %%2

79.開源程序庫Xercesc-C++代碼工程中內聯80.提取包含頭文件列表
#!/bin/bash

81.GB2312文件轉Unicode格式
#!/bin/sh
iconv -f gbk -t  ucs2 %%1 -o %%2

82.Java程序打包
#!/bin/bash

83.UTF-8文件轉Unicode格式
#!/bin/bash
iconv -f utf8 -t  ucs2 %%1 -o %%2

84.創建PDF文檔
#!/bin/bash

85.創建Word文檔
#!/bin/bash

86.快速高效的文件加密
#!/bin/bash

87.從CSV文件構造XML文檔
#!/bin/bash

88.從XML文檔生成CSV文件
#!/bin/bash

89.模擬鍵盤輸入字符串
#!/bin/bash

90.提取PDF文件中的文本
#!/bin/bash

91.操作內存映射文件
#!/bin/bash
91.1發送內存映射數據
#!/bin/bash

91.2接收內存映射數據
#!/bin/bash

92.重定向windows控制檯程序的輸出信息
#!/bin/bash

93.基數轉序數
#!/bin/bash

94.數字月份轉英文
#!/bin/bash

95.報表相關
#!/bin/bash

96.根據進程名獲取進程ID
#!/bin/bash
pidof %%1 -s

96.BCP導入
#!/bin/bash

97.BCP導出
#!/bin/bash


98.計算文件MD5值
#!/bin/bash
md5sum "%%1"

99.計算獲取文件夾中文件的MD5值
#!/bin/bash

100.複製一個目錄下所有文件到一個文件夾中
#!/bin/bash
cp $(find "%%1" -name *.*) "%%2"

101.移動一個目錄下所有文件到一個文件夾中
#!/bin/bash
mv $(find "%%1" -name *.*) "%%2"

102.文件RSA高級加密
十進制到十六進制
typeset -i16 BASE_16_NUM
BASE_16_NUM=%%1
echo $BASE_16_NUM

八進制到十六進制
#!/bin/bash
typeset -i16 BASE_16_NUM
BASE_16_NUM=8#%%1
echo $BASE_16_NUM

十進制到八進制
#!/bin/bash
printf %o %%1; echo

十進制到十六進制
#!/bin/bash
printf %x %%1; echo

103.計算文件大小
#!/bin/bash
wc "%%1"

104.計算文件夾的大小
#!/sbin/ksh
dir=%%1
(cd $dir;pwd)
find $dir -type d -print | du | awk '{print $2, "== ("$1/2"kb)"}' |sort -f |
sed -e "s,[^ /]*/([^ /]*) ==,|--1," -e"s,[^ /]*/,| ,g"

105.快速獲得當前程序的驅動器、路徑、文件名和擴展名

106.磁盤剩餘空間計算
#!/bin/bash
df -k

107.獲取當前程序進程ID
#!/bin/bash
pidof %%1 -s

108.全盤搜索文件
#!/bin/bash
#updatedb
#locate %%1
slocate %%1

109.獲得當前登錄的用戶名
#!/bin/bash
whoami

110.獲得所有用戶名
#!/bin/bash
who

111.創建MySQL管理用戶
#!/bin/bash
mysqladmin -u root password %%1

112.管理MySQL數據庫服務器
#!/bin/bash
112.1.啓動MySQL數據庫服務器
mysqld -console

112.2.登錄MySQL數據庫服務器
112.2.1.登錄本地MySQL數據庫服務器
mysql -uroot -p%%1

112.2.2.登錄遠程MySQL數據庫服務器
mysql -h %%1 -u %%2 -p%%3

112.3.關閉MySQL數據庫服務器
mysqladmin -u root shutdown
#pkill -9 mysql

112.4.測試MySQL數據庫服務器
mysqlshow || mysqlshow -u root mysql || mysqladmin version status || mysql test

113.MySQL執行查詢
#!/bin/sh
mysqladmin -u %%1 -p%%2 SELECT * INTO OUTFILE './bestlovesky.xls' FROM bestlovesky WHERE 1 ORDER BY id DESC  LIMIT 0, 50;

mysql -u %%1 -p%%2 -e "SELECT * INTO OUTFILE './bestlovesky.xls' FROM bestlovesky WHERE 1 ORDER BY id DESC  LIMIT 0, 50;"

114.創建Oracle管理用戶
#!/bin/sh
114.1.創建新用戶
create user test identified by test default tablespace ts_test temporary
tablespace temp;

114.2.給用戶角色特權
grant connect,resource to test;

115.登錄Oracle數據庫
#!/bin/bash
sqlplusw
sqlplus /nolog
conn username/password@Oranet
conn system/systempwd@whfc
conn sys/syspwd@whfc as sysdba

115.創建Oracle表空間
#!/bin/bash
conn system@whfc01
create tablespace ts_test datafile '/data2/oradata/ciis/ts_test01.dbf' size

116.添加Oracle數據文件
#!/bin/bash
alter tablespace ts_test add datafile '/data2/oradata/ciis/ts_test02.dbf' size

117.查看Oracle表空間大小
#!/bin/bash
desc DBA_DATA_FILES

118.查看Oracle剩餘表空間大小
#!/bin/bash
desc DBA_FREE_SPACE

119.查看Oracle當前用戶表名
#!/bin/bash
select * from tab;

120.Oracle創建索引
#!/bin/bash
CREATE INDEX idx_book_bookid ON book(bookname);

121.Oracle創建主鍵約束
#!/bin/bash
ALTER TABLE book ADD CONSTRAINT pk_book_bookid PRIMARY KEY (bookid);

122.Oracle顯示錶結構
#!/bin/bash
desc book

123.Oracle查看錶的索引
#!/bin/bash
column index_name format a30
select table_name, index_name from user_indexes;

124.Oracle查看索引列
#!/bin/bash
select table_name, index_name, column_name, column_position from user_ind_columns;

125.Oracle查看數據段佔空間大小
#!/bin/bash
desc user_segments

126.Oracle查看錶佔空間大小
#!/bin/bash
select segment_name,segment_type,bytes from user_segments where segment_type='TABLE';

127.安全刪除USB
#!/bin/bash
rundll32.exe shell32.dll,Control_RunDLL hotplug.dll

128.打開SQL Server Management Studio
#!/bin/bash
sqlwb %%1.sql

129.MySQL數據庫導出備份
#!/bin/bash
mysqldump -u %%1 -p %%2 %%3>%%4.sql
mysqldump --opt test > mysql.test //將數據庫test導出到mysql.test文件,後面是一個文本文件
mysqldump -u root -p123456 --databases dbname > mysql.dbname //就是把數據庫dbname導出到文件mysql.dbname中。

130.MySQL數據庫數據導入
mysql -u %%1 -p %%2 %%3<%%4.sql
mysqlimport -u root -p123456 < mysql.dbname
將文本數據導入數據庫:
文本數據的字段之間用tab鍵隔開
use test
load data local infile "文件名" into table 表名;
eg: load data local infile "D:/mysql.txt" into table mytable;
導入.sql 文件命令
use database
source d:/mysql.sql;

131.MySQL數據庫檢查
mysqlcheck -o %%3 -u %%1 -p %%2

132.MySQL數據表文件修復
myisamchk -B -o %%1.myd

1,查看數據庫狀態 及啓動停止
/etc/init.d/mysqld status
/etc/init.d/mysqld start
/etc/init.d/mysqld stop

2,給用戶配置初始密碼123456:
mysqladmin -u root -password 123456

3,修改root用戶密碼爲 abc123
mysqladmin -u root -p123456 password abc123

4,如果想去掉密碼:
mysqladmin -u root -pabc123 password ""

5,root連接數據庫有密碼和無密碼:
mysql -u root(-uroot) -p
mysql

6,增加用戶 test1 密碼 abc,讓它可以在任何主機上登錄,並對所有數據庫有查詢,插入,修改,刪除的權限:
格式: grant select on 數據庫.* to 用戶名@登錄主機 identified by "密碼"
grant select,insert,update,delete on *.* to test1@"%" Identified by "abc";

8,增加一個用戶test2,讓它只可以在localhost上登錄,並可以對數據庫mydb進行查詢,插入,修改,刪除的操作,
這樣用戶即使使用知道test2的密碼,他也無法從internet 上直接訪問數據庫,只能通過mysql主機上的web頁面來訪問。
grant select,insert,update,delete on mydb.* to test2@localhost identified by "abc";
grant select,insert,update,delete on mydb.* to test2@localhost identified by ""; 設置無密碼

9,顯示數據庫列表:
show databases;
use mysql 打開庫
show tables;

10,表的操作
describle 表名; 顯示數據表的結構
create database 庫名;
drop database 庫名;
create table 表名(字段設定列表)
drop table 表名;
delete from 表名;清空表記錄
select * from 表名; 顯示錶中的記錄
insert into 表名 values(, ,)

alter table 表名 add column <字段名><字段選項>

133.檢查端口占用
#!/bin/bash
netstat -ano

134.Linux下檢查Apache是否安裝
#!/bin/bash
rpm -qa | grep httpd

135.Linux下啓動Apache服務
#!/bin/bash
service httpd start

136.Linux下停止Apache服務
#!/bin/bash
service httpd stop

137.Linux下重新啓動Apache服務
#!/bin/bash
service httpd restart

138.Linux下自動加載Apache 服務
#!/bin/bash
chkconfig - level 3 httpd on

139.Linux下不自動加載Apache 服務
#!/bin/bash
chkconfig - level 3 httpd off

140.Linux下檢查VSFTP是否安裝
#!/bin/bash
rpm -qa | grep vsftpd

141.Linux下啓動VSFTP服務
#!/bin/bash
service vsftpd start

142.Linux下停止VSFTP服務
#!/bin/bash
service vsftpd stop

143.Linux下重新啓動VSFTP服務
#!/bin/bash
service vsftpd restart

144.Linux下檢查VSFTP是否被啓動
#!/bin/bash
pstree | grep vsftpd

145.Linux下檢查Sendmail是否安裝
#!/bin/bash
rpm -qa | grep sendmail

146.Linux下啓動Sendmail服務
#!/bin/bash
service sendmail start

147.Linux下停止Sendmail服務
#!/bin/bash
service sendma stop

148.Linux下重新啓動Sendmail服務
#!/bin/bash
service sendmail restart

149.Linux下自動加載Sendmail 服務
#!/bin/bash
chkconfig - level 3 sendmail on

150.Linux下不自動加載Sendmail 服務
#!/bin/bash
chkconfig - level 3 sendmail off

151.Linux下文本圖形界面配置啓動服務
#!/bin/bash
ntsysv

152.以數組的方式刪除文件夾

153.GCC批量編譯
#!/bin/bash
find -type f \( -iname '*.c' -o -iname '*.cpp' \) -print |
while read filename
do
    case "$filename" in
    *.c)
      gcc "$filename" -o "$(dirname "$filename")"/"$(basename "$filename" .c)"
        ;;
    *.cpp)
        gcc "$filename" -o "$(dirname "$filename")"/"$(basename "$filename" .cpp)"
        ;;
    esac
done

154.批量賦予可執行權限
#!/bin/bash
find "$PWD" -type f \( -iname '*.sh' -o  -iname '*.csh' -o  -iname '*.ksh' -o -iname '*.pl' -o -iname '*.bin' -o -iname '*.run' -o -iname '*.bundle' -o -iname '*.rb' -o -iname '*.py' \) -print0 | xargs -0 chmod +x

#!/bin/bash
for file in *.sh *.pl *.bin *.run *.bundle *.rb *.py
do
if [[ ! "$file" =~ \*.[A-Za-z]+ ]]; then
chmod +x "$(file)"
fi
done
OLDIFS=$IFS
IFS=:
for path in $( find $(pwd) -type d -printf "%p$IFS")
do
for file in $path/*.sh $path/*.pl $path/*.bin $path/*.run $path/*.bundle $path/*.rb $path/*.py
do
if [[ ! "$file" =~ \*.[A-Za-z]+ ]]; then
chmod +x "$(path)/$(file)"
fi
done
done
IFS=$OLDIFS

155.批量執行
#!/bin/bash
find -type f \( -iname '*.sh' -o  -iname '*.csh' -o  -iname '*.ksh' -o -iname '*.pl' -o -iname '*.bin' -o -iname '*.run' -o -iname '*.bundle' -o -iname '*.bin' -o -iname '*.class' -o -iname '*.rpm' -o -iname '*.rb' -o -iname '*.py' -o -iname '*.jar' \) -print |
while read filename
do
    case "$filename" in
    *.sh | *.csh | *.ksh)
if [ ! "./""$(basename $filename)" = $0 ]; then
        xterm -e "$filename"
fi
        ;;
    *.pl)
        xterm -e perl "$filename"
        ;;
    *.bin | *.run | *.bundle)
        xterm -e "$filename"
        ;;
    *.class)
        xterm -e java "$(dirname "$filename")"/"$(basename "$filename" .class)"
        ;;
    *.rpm)
        xterm -e rpm -ivh "$filename"
        ;;
    *.rb)
        xterm -e ruby "$filename"
        ;;
    *.py)
        xterm -e python "$filename"
        ;;
    *.jar)
        xterm -e java -jar "$filename"
        ;;
    esac
done

#!/bin/bash
find -maxdepth 1 -type f \( -iname '*.sh' -o -iname '*.pl' -o -iname '*.bin' -o -iname '*.run' -o -iname '*.bundle' -o -iname '*.bin' -o -iname '*.class' -o -iname '*.rpm' -o -iname '*.rb' -o -iname '*.py' -o -iname '*.jar' \) -print
while read file
do
    case "${file##*.}" in
        sh ) xterm -e """"$file"""";;
        pl ) xterm -e perl """"$file"""";;
        bin ) xterm -e """"$file"""";;
        run ) xterm -e """"$file"""";;
        bundle ) xterm -e """"$file"""";;
        class ) xterm -e java """"${file%.*}"""";;
        rpm ) xterm -e rpm -ivh """"$file"""";;
        rb ) xterm -e ruby """"$file"""";;
        py ) xterm -e python """"$file"""";;
        jar ) xterm -e java -jar """"$file"""";;
    esac
done

156.獲取操作系統版本
#!/bin/bash
uname -r
#uname -a

157.自身複製
#!/bin/bash
cp $0 "%%1"

158.GCC批量創建靜態庫
#!/bin/bash
find -type f \( -iname '*.c' -o -iname '*.cpp' \) -print |
while read filename
do
    case "$filename" in
    *.c)
      g++  -c -o "$(dirname "$filename")"/"$(basename "$filename" .c)".o"" "$filename"
        ;;
    *.cpp)
      g++  -c -o "$(dirname "$filename")"/"$(basename "$filename" .cpp)".o"" "$filename"
        ;;
    esac
done
OLDIFS=$IFS
IFS=:
for path in $( find $(pwd) -type d -printf "%p$IFS")
do
ar ru $path".a" $path"/*.o" && ranlib $path".a"
done
IFS=$OLDIFS
find "$PWD" -type f \( -iname '*.o' \) -print0 | xargs -0 rm -if

159.Java批量打包EJB
#!/bin/bash
find "$PWD" -type f \( -iname '*.java' \) -print0 | xargs -0 javac
OLDIFS=$IFS
IFS=:
for path in $( find $(pwd) -type d -printf "%p$IFS")
do
jar -cvf "$(path".jar")" "$(path"/*.*")" && cp "$(path".jar")" "$(JBOSS_HOME"/server/default/deploy")"
done
IFS=$OLDIFS

find "$PWD" -type f \( -iname '*.class' \) -print0 | xargs -0 rm -if

160.獲取環境變量

161.dd
#!/bin/bash
dd

162.顯示只有小寫字母的文件
#!/bin/bash
ls -1|awk '/^[[:lower:]].*/'

163.Zip壓縮目錄中的所有文件
#!/bin/bash
direc="%%1" #$(pwd)
targetpath="%%2"
OLDIFS=$IFS
IFS=:
for path in $( find $direc -type d -printf "%p$IFS")
do
mkdir -p "$targetpath/${path:${#direc}+1}"
for file in $path/*
do
if [ -f $file ]; then
zip -j "$targetpath/${path:${#direc}+1}/${file:${#path}+1}.zip" "$file"
fi
done
done
IFS=$OLDIFS

164.Zip解壓縮目錄中的所有文件
#!/bin/bash
direc="%%1" #$(pwd)
targetpath="%%2"
OLDIFS=$IFS
IFS=:
for path in $( find $direc -type d -printf "%p$IFS")
do
mkdir -p "$targetpath/${path:${#direc}+1}"
unzip -x "$path/*.zip" -d "$targetpath/${path:${#direc}+1}"
done
IFS=$OLDIFS

165.分佈式複製文件夾
#!/bin/bash
direc="%%1" #$(pwd)
targetpath="%%2"
OLDIFS=$IFS
IFS=:
for path in $( find $direc -type d -printf "%p$IFS")
do
mkdir -p "$targetpath/${path:${#direc}+1}"
rm -if "$targetpath/${path:${#direc}+1}/*.tmp"
for file in $path/*
do
if [ -f $file ]; then
cp "$file" "$targetpath/${path:${#direc}+1}/${file:${#path}+1}.tmp"
mv "$targetpath/${path:${#direc}+1}/${file:${#path}+1}.tmp" "$targetpath/${path:${#direc}+1}/${file:${#path}+1}"
fi
done
done
IFS=$OLDIFS

166.註冊反註冊組件
#!/bin/bash
regsvr32 "%%1"

167.LZMA
#!/bin/bash

168.CAB壓縮文件
#!/bin/bash

169.CAB解壓縮文件
#!/bin/bash


170.鎖定屏幕
#!/bin/sh
RUNDLL32.exe USER32,LockWorkStation

171.以其它用戶的身份運行程序
#!/bin/bash

172.添加系統用戶
#!/bin/sh
useradd "%%1"

173.刪除系統用戶
#!/bin/sh
userdel "%%1"

174.添加用戶組
#!/bin/sh
groupadd -g 2000 "%%1"

175.刪除用戶組
#!/bin/sh
groupdel "%%1"

176.賦予管理員權限
#!/bin/bash


177.收回管理員權限
#!/bin/bash


178.遍歷目錄產生刪除文件的腳本
#!/bin/bash


179.LZW壓縮文件
#!/bin/bash
z

180.LZW解壓縮文件
#!/bin/bash
z

181.遞歸賦予目錄權限
#!/bin/bash
direc="%%1" #$(pwd)
OLDIFS=$IFS
IFS=:
for path in $( find $direc -type d -printf "%p$IFS")
do
chown -R root.root "$path"
done
IFS=$OLDIFS

182.卸載RPM包
#!/bin/sh
rpm -e  "%%1"

183.刪除源文件中的註釋
#!/bin/sh

184.設置目錄下所有文件屬性爲可寫
#!/bin/sh

185.統計目錄下所有文件的總共行數
#!/bin/sh
cat * |wc
ls *|xargs wc -l
find ./ -name "*c" | xargs wc -l

186.刪除自身
#!/bin/rm
exit 65
#rm $0

187.打開終端
#!/bin/bash -l

188.彈出光驅
#!/bin/sh
eject

189.收回光驅
#!/bin/sh
eject -t

190.磁盤總空間計算

191.解析CSV文件

192.按行保存文件爲數組

193.MySQL執行SQL文件
mysqladmin -u %%1 -p%%2 < %%3.sql

mysql -u %%1 -p%%2 -e "SOURCE %%3.sql"

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章