Linux常用命令大全(非常全面!!!)

目錄

一、進程管理 

二、系統信息 

三、關機 (系統的關機、重啓以及登出 ) 

四、文件和目錄 

五、文件搜索 

六、掛載一個文件系統 

七、磁盤空間 

八、系統負載 -- top 

九、用戶和羣組 

十、文件的權限 - 使用 "+" 設置權限,使用 "-" 用於取消 

十一、文件的特殊屬性 - 使用 "+" 設置權限,使用 "-" 用於取消 

十二、打包和壓縮文件 

十三、OS包管理器

①、RPM 包 - (Fedora, Redhat及類似系統) 

②、YUM 軟件包升級器 - (Fedora, RedHat及類似系統) 

③、DEB 包 (Debian, Ubuntu 以及類似系統) 

④、APT 軟件工具 (Debian, Ubuntu 以及類似系統) 

十四、文本查看、處理

①、查看文件內容 

②、文本處理 

十五、vim專題 

①、大小寫轉換

②、字符串處理專題

③、vi中文本操作

十五、字符設置和文件格式轉換 

十六、文件系統分析 

十七、初始化一個文件系統 

十八、SWAP文件系統 

十九、備份 

二十、光盤操作 

二一、網絡 - (以太網和WIFI無線) 

二二、JPS工具

二三、Shell編程相關

①、內置變量

②、數據結構

1、數組

2、字典dict 或 Map

3、管道輸出中執行下一條指令

4、循環、迭代邏輯控制

5、break 與 contine區別

6、大文件拆分處理

7、awk



 

Linux和windows相比,很多管控都需要用命令來操作。windows以直觀的可視化的方式操作,特別適合在桌面端PC上操作執行相應的軟件。

而Linux命令行方式的操作,特別是在服務器端編程、管理、運維方面,更加簡單、短小、精悍。短短一行組合命令,即可完成在windows需要各種加工、整合的複雜高效的功能操作。 

 

一、進程管理 


w 顯示當前在線用戶情況

my_adm pts/0    111.111.111.111    三15   24:58   2:51   0.02s sshd: my_admin [priv]
root     pts/3    111.111.111.112      13:15    3:47m  0.35s  0.35s -bash
my_adm pts/5    111.111.111.113    15:14    2.00s  0.54s  0.02s sshd: my_admin [priv]

pkill -kill -t pts/??  殺掉指定名字的進程,如上述的pts/5

 

二、系統信息 


arch 顯示機器的處理器架構(1) 
uname -m 顯示機器的處理器架構(2) 
uname -r 顯示正在使用的內核版本 
dmidecode -q 顯示硬件系統部件 - (SMBIOS / DMI) 
hdparm -i /dev/hda 羅列一個磁盤的架構特性 
hdparm -tT /dev/sda 在磁盤上執行測試性讀取操作 
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 顯示已加載的文件系統 
lspci -tv 羅列 PCI 設備 
lsusb -tv 顯示 USB 設備 
date 顯示系統日期 
cal 2007 顯示2007年的日曆表 
date 041217002007.00 設置日期和時間 - 月日時分年.秒 
clock -w 將時間修改保存到 BIOS 

查詢網關地址(如將centos服務器網絡獲取類型由dhcp切換爲static時,需要獲取到ip及網關信息進行固化配置時會用到,如本地ip爲10.34.0.123,則通過如下命令查詢到網關爲第一個3.254):

[root@file-server ~]# netstat -rn
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
0.0.0.0         10.34.3.254     0.0.0.0         UG        0 0          0 enp3g0
10.34.0.0       0.0.0.0         255.255.252.0   U         0 0          0 enp3g0
192.168.1.0     0.0.0.0         255.255.255.0   U         0 0          0 virbr0

CentOS / RedHat 系列,查看操作系統信息(如果沒有lsb_release命令, 使用"yum install redhat-lsb"安裝):

[root@server-test online]# lsb_release -a
LSB Version:	:core-4.1-amd64:core-4.1-noarch
Distributor ID:	CentOS
Description:	CentOS Linux release 7.5.1804 (Core) 
Release:	7.5.1804
Codename:	Core


三、關機 (系統的關機、重啓以及登出 ) 


shutdown -h now 關閉系統(1) 
init 0 關閉系統(2) 
telinit 0 關閉系統(3) 
shutdown -h hours:minutes & 按預定時間關閉系統 
shutdown -c 取消按預定時間關閉系統 
shutdown -r now 重啓(1) 
reboot 重啓(2) 
logout 註銷 


四、文件和目錄 


cd /home 進入 '/ home' 目錄' 
cd .. 返回上一級目錄 
cd ../.. 返回上兩級目錄 
cd 進入個人的主目錄 
cd ~user1 進入個人的主目錄 
cd - 返回上次所在的目錄 
pwd 顯示工作路徑 
ls 查看目錄中的文件 
ls -F 查看目錄中的文件 
ls -l 顯示文件和目錄的詳細資料 
ls -a 顯示隱藏文件 
ls *[0-9]* 顯示包含數字的文件名和目錄名 
tree 顯示文件和目錄由根目錄開始的樹形結構(1) 
lstree 顯示文件和目錄由根目錄開始的樹形結構(2) 
mkdir dir1 創建一個叫做 'dir1' 的目錄' 
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類系統) 

hdfs dfs -du /dw/default | sort -rn | head -n 10 | awk '{printf("%.2f\t\t%.2f\t\t%s\t\n",$1/1024/1024/1024,"\t"$2/1024/1024/1024,"\t"$3)}'  查詢hdfs文件系統中表文件大小,按從大到小的順序排列(取前10列),單位GB

 

八、系統負載 -- top 


top -d 20 -p 1303                             將進程號1303的系統負載,每隔20秒刷新一次。英文狀態下,按住c鍵,將展示進行的詳細環境信息,對於java程序調試來說,非常友好。 
top -d 20 -n 3 -b > test.txt                  每隔20秒,一共執行3次, 將統計結果導入到test.txt文件中。           

其他參數列表,官方解釋: 

1. COMMAND-LINE Options
       The command-line syntax for top consists of:

         -hv|-bcHiOSs -d secs -n max -u|U user -p pid -o fld -w [cols]

       The typically mandatory switch ('-') and even whitespace are completely optional.

       -h | -v  :Help/Version
            Show library version and the usage prompt, then quit.

       -b  :Batch-mode operation
            Starts top in Batch mode, which could be useful for sending output from top to other programs or to a file.  In this mode, top will not accept input and runs until the iterations limit you've set with the `-n' command-line option or until killed.

       -c  :Command-line/Program-name toggle
            Starts top with the last remembered `c' state reversed.  Thus, if top was displaying command lines, now that field will show program names, and visa versa.  See the `c' interactive command for additional information.

       -d  :Delay-time interval as:  -d ss.t (secs.tenths)
            Specifies the delay between screen updates, and overrides the corresponding value in one's personal configuration file or the startup default.  Later this can be changed with the `d' or `s' interactive commands.

            Fractional  seconds  are honored, but a negative number is not allowed.  In all cases, however, such changes are prohibited if top is running in Secure mode, except for root (unless the `s' command-line option was used).  For additional information on
            Secure mode see topic 6a. SYSTEM Configuration File.

       -H  :Threads-mode operation
            Instructs top to display individual threads.  Without this command-line option a summation of all threads in each process is shown.  Later this can be changed with the `H' interactive command.

       -i  :Idle-process toggle
            Starts top with the last remembered `i' state reversed.  When this toggle is Off, tasks that have not used any CPU since the last update will not be displayed.  For additional information regarding this toggle see topic 4c. TASK AREA Commands, SIZE.

       -n  :Number-of-iterations limit as:  -n number
            Specifies the maximum number of iterations, or frames, top should produce before ending.

       -o  :Override-sort-field as:  -o fieldname
            Specifies the name of the field on which tasks will be sorted, independent of what is reflected in the configuration file.  You can prepend a `+' or `-' to the field name to also override the sort direction.  A leading `+' will force sorting  high  to
            low, whereas a `-' will ensure a low to high ordering.

            This option exists primarily to support automated/scripted batch mode operation.

       -O  :Output-field-names
            This option acts as a form of help for the above -o option.  It will cause top to print each of the available field names on a separate line, then quit.  Such names are subject to nls translation.

       -p  :Monitor-PIDs mode as:  -pN1 -pN2 ...  or  -pN1,N2,N3 ...
            Monitor only processes with specified process IDs.  This option can be given up to 20 times, or you can provide a comma delimited list with up to 20 pids.  Co-mingling both approaches is permitted.

            A pid value of zero will be treated as the process id of the top program itself once it is running.

            This is a command-line option only and should you wish to return to normal operation, it is not necessary to quit and restart top  --  just issue any of these interactive commands: `=', `u' or `U'.

            The `p', `u' and `U' command-line options are mutually exclusive.

       -s  :Secure-mode operation
            Starts top with secure mode forced, even for root.  This mode is far better controlled through the system configuration file (see topic 6. FILES).

       -S  :Cumulative-time toggle
            Starts  top  with  the  last  remembered `S' state reversed.  When Cumulative time mode is On, each process is listed with the cpu time that it and its dead children have used.  See the `S' interactive command for additional information regarding this
            mode.

       -u | -U  :User-filter-mode as:  -u | -U number or name
            Display only processes with a user id or user name matching that given.  The `-u' option matches on  effective user whereas the `-U' option matches on any user (real, effective, saved, or filesystem).

            Prepending an exclamation point ('!') to the user id or name instructs top to display only processes with users not matching the one provided.

            The `p', `u' and `U' command-line options are mutually exclusive.

       -w  :Output-width-override as:  -w [ number ]
            In Batch mode, when used without an argument top will format output using the COLUMNS= and LINES= environment variables, if set.  Otherwise, width will be fixed at the maximum 512 columns.  With an argument, output width can be decreased or  increased
            (up to 512) but the number of rows is considered unlimited.

            In normal display mode, when used without an argument top will attempt to format output using the COLUMNS= and LINES= environment variables, if set.  With an argument, output width can only be decreased, not increased.  Whether using environment vari‐
            ables or an argument with -w, when not in Batch mode actual terminal dimensions can never be exceeded.

            Note: Without the use of this command-line option, output width is always based on the terminal at which top was invoked whether or not in Batch mode.

 


九、用戶和羣組 

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' 
unrar x file1.rar 解壓rar包   #如果無unrar命令,參考:http://www.360doc.com/content/17/0426/21/41572081_648911802.shtml
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格式壓縮包 


十三、OS包管理器

①、RPM 包 - (Fedora, Redhat及類似系統) 

rpm -ivh package.rpm 安裝一個rpm包 
rpm -ivh --nodeps package.rpm 安裝一個rpm包而忽略依賴關係警告 
rpm -U package.rpm 更新一個rpm包但不改變其配置文件 
rpm -F package.rpm 更新一個確定已經安裝的rpm包 
rpm -e [--nodeps] package_name.rpm 刪除一個rpm包[--nodeps表示忽略依賴關係] 
rpm -qa 顯示系統中所有已經安裝的rpm包 
rpm -qa | grep httpd 顯示所有名稱中包含 "httpd" 字樣的rpm包 
rpm -qi package_name 獲取一個已安裝包的特殊信息 
rpm -qg "System Environment/Daemons" 顯示一個組件的rpm包 
rpm -ql package_name 顯示一個已經安裝的rpm包提供的文件列表 
rpm -qc package_name 顯示一個已經安裝的rpm包提供的配置文件列表 
rpm -q package_name --whatrequires 顯示與一個rpm包存在依賴關係的列表 
rpm -q package_name --whatprovides 顯示一個rpm包所佔的體積 
rpm -q package_name --scripts 顯示在安裝/刪除期間所執行的腳本l 
rpm -q package_name --changelog 顯示一個rpm包的修改歷史 
rpm -qf /etc/httpd/conf/httpd.conf 確認所給的文件由哪個rpm包所提供 
rpm -qp package.rpm -l 顯示由一個尚未安裝的rpm包提供的文件列表 
rpm --import /media/cdrom/RPM-GPG-KEY 導入公鑰數字證書 
rpm --checksig package.rpm 確認一個rpm包的完整性 
rpm -qa gpg-pubkey 確認已安裝的所有rpm包的完整性 
rpm -V package_name 檢查文件尺寸、 許可、類型、所有者、羣組、MD5檢查以及最後修改時間 
rpm -Va 檢查系統中所有已安裝的rpm包- 小心使用 
rpm -Vp package.rpm 確認一個rpm包還未安裝 
rpm2cpio package.rpm | cpio --extract --make-directories *bin* 從一個rpm包運行可執行文件 
rpm -ivh /usr/src/redhat/RPMS/`arch`/package.rpm 從一個rpm源碼安裝一個構建好的包 
rpmbuild --rebuild package_name.src.rpm 從一個rpm源碼構建一個 rpm 包 


②、YUM 軟件包升級器 - (Fedora, RedHat及類似系統) 


yum install package_name 下載並安裝一個rpm包 
yum localinstall package_name.rpm 將安裝一個rpm包,使用你自己的軟件倉庫爲你解決所有依賴關係 
yum update package_name.rpm 更新當前系統中所有安裝的rpm包 
yum update package_name 更新一個rpm包 
yum remove package_name 刪除一個rpm包 
yum list 列出當前系統中安裝的所有包 
yum search package_name 在rpm倉庫中搜尋軟件包 
yum clean packages 清理rpm緩存刪除下載的包 
yum clean headers 刪除所有頭文件 
yum clean all 刪除所有緩存的包和頭文件 


③、DEB 包 (Debian, Ubuntu 以及類似系統) 

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 軟件工具 (Debian, Ubuntu 以及類似系統) 

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" 

grep -Hnr docker * 在本層或子文件夾裏遞歸查找包含指定字符“docker”的文件,並顯示文件名+行號,如果精確匹配文本,加o參數。參數含義:(H:每次匹配時將文件名打印出來;n:打印字符串所在的行號;r:遞歸查找;o:精確匹配到單詞,多一個字符都不行)
sed 's/string1/string2/g' example.txt 將example.txt文件中的 "string1" 替換成 "string2" 
sed '/^$/d' example.txt 從example.txt文件中刪除所有空白行 
sed '/ *#/d; /^$/d' example.txt 從example.txt文件中刪除所有註釋和空白行 
echo 'hElloWorld' | tr '[:lower:]' '[:upper:]' 找出所有的小寫字母並全部替換爲大寫字母 
sed -e '1d' result.txt 從文件example.txt 中排除第一行 
sed -n '/string1/p' 查看只包含詞彙 "string1"的行 
sed -e 's/ *$//' example.txt 刪除每一行最後的空白字符 
sed -e 's/string1//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 用單個零替換多個零

sed -i '3i helloword' test.txt   在test.txt文件的第三行插入‘helloword’字符串
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 比較兩個文件的內容只刪除兩個文件共有的部分 

綜合案例:本機tcp各種狀態數統計

netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'
CLOSE_WAIT 2
ESTABLISHED 276
SYN_SENT 2
TIME_WAIT 63270


awk 'BEGIN {
   sum = 0; for (i = 0; i < 20; ++i) {
      sum += i; if (sum > 50) exit(10); else print "Sum =", sum 
   } 
}'

 

十五、vim專題 

①、大小寫轉換

: https://blog.csdn.net/guowake/article/details/2217086

 

②、字符串處理專題

總結:

掐頭(刪左側: ①#:刪左側;②##:貪婪刪左側)去尾(刪右側: ①%:刪右邊;②%%:貪婪刪右側)

1、linux shell 字符串操作詳解 (長度,讀取,替換,截取,連接,對比,刪除,位置 )

2、Linux Bash Shell字符串截取

3、Shell 截取字符串

4、shell腳本字符串截取的8種方法

5. Linux-shell腳本字符串截取

6. linux中shell變量$#,$@,$0,$1,$2的含義解釋/Shell中的${}、##和%%使用範例/export

7.Shell 命令中的特殊替換、模式匹配替換、字符串提取和替換

8.shell變量裏的字符替換

 

③、vi中文本操作

vi/vim 中在每行行首或行尾插入指定字符串

行首 :%s/^/your_word/
行尾 :%s/$/your_word/

按鍵操作:

註釋(列模式方式):ctrl+v 進入列編輯模式,向下或向上移動光標,把需要註釋的行的開頭標記起來,然後按大寫的I,再插入註釋符,比如”#”,再按Esc,就會全部註釋了。

刪除:先按v,進入visual模式,橫向選中列的個數(如”#”註釋符號,需要選中兩列),再按Esc,再按ctrl+v 進入列編輯模式,向下或向上移動光標,選中註釋部分,然後按d, 就會刪除註釋符號(#)。

PS:當然不一定是shell的註釋符”#”,也可以是”//”,或者其他任意的字符;vim纔不知道什麼是註釋符呢,都是字符而已。

使用替換命令:

在全部內容的行首添加//號註釋
:% s/^/\/\//g

在2~50行首添加//號註釋
:2,50 s/^/\/\//g

在2~50行首刪除//號
:2,50 s/^\/\///g


十五、字符設置和文件格式轉換 

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文件系統 


十八、SWAP文件系統 

mkswap /dev/hda3 創建一個swap文件系統 
swapon /dev/hda3 啓用一個新的swap文件系統 
swapon /dev/hda2 /dev/hdb3 啓用兩個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 


二一、網絡 - (以太網和WIFI無線) 


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(1) 
nslookup www.example.com lookup hostname to resolve name to ip address and viceversa(2) 
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 

 

二二、JPS工具

jps(Java Virtual Machine Process Status Tool)是JDK 1.5提供的一個顯示當前所有java進程pid的命令,簡單實用,非常適合在linux/unix平臺上簡單察看當前java進程的一些簡單情況。

    我想很多人都是用過unix系統裏的ps命令,這個命令主要是用來顯示當前系統的進程情況,有哪些進程,及其 id。 jps 也是一樣,它的作用是顯示當前系統的java進程情況,及其id號。我們可以通過它來查看我們到底啓動了幾個java進程(因爲每一個java程序都會獨佔一個java虛擬機實例),和他們的進程號(爲下面幾個程序做準備),並可通過opt來查看這些進程的詳細啓動參數。

     使用方法:在當前命令行下打 jps(需要JAVA_HOME,沒有的話,到改程序的目錄下打) 。

jps存放在JAVA_HOME/bin/jps,使用時爲了方便請將JAVA_HOME/bin/加入到Path.

$> jps
23991 Jps
23789 BossMain
23651 Resin

 


比較常用的參數:

-q 只顯示pid,不顯示class名稱,jar文件名和傳遞給main 方法的參數
$>  jps -q
28680
23789
23651

-m 輸出傳遞給main 方法的參數,在嵌入式jvm上可能是null

$> jps -m
28715 Jps -m
23789 BossMain
23651 Resin -socketwait 32768 -stdout /data/aoxj/resin/log/stdout.log -stderr /data/aoxj/resin/log/stderr.log

-l 輸出應用程序main class的完整package名 或者 應用程序的jar文件完整路徑名

$> jps -l
28729 sun.tools.jps.Jps
23789 com.asiainfo.aimc.bossbi.BossMain
23651 com.caucho.server.resin.Resin

-v 輸出傳遞給JVM的參數

$> jps -v
23789 BossMain
28802 Jps -Denv.class.path=/data/aoxj/bossbi/twsecurity/java/trustwork140.jar:/data/aoxj/bossbi/twsecurity/java/:/data/aoxj/bossbi/twsecurity/java/twcmcc.jar:/data/aoxj/jdk15/lib/rt.jar:/data/aoxj/jd

k15/lib/tools.jar -Dapplication.home=/data/aoxj/jdk15 -Xms8m
23651 Resin -Xss1m -Dresin.home=/data/aoxj/resin -Dserver.root=/data/aoxj/resin -Djava.util.logging.manager=com.caucho.log.LogManagerImpl -

Djavax.management.builder.initial=com.caucho.jmx.MBeanServerBuilderImpl

sudo jps看到的進程數量最全

jps 192.168.0.77

列出遠程服務器192.168.0.77機器所有的jvm實例,採用rmi協議,默認連接端口爲1099

(前提是遠程服務器提供jstatd服務)

注:jps命令有個地方很不好,似乎只能顯示當前用戶的java進程,要顯示其他用戶的還是隻能用unix/linux的ps命令。

 

詳細情況請參考sun官方文檔。
http://java.sun.com/j2se/1.7.0/docs/tooldocs/share/jps.html

GO TOP INDEX ^ 
Microsoft Windows networks (SAMBA) 
nbtscan ip_addr netbios name resolution 
nmblookup -A ip_addr netbios name resolution 
smbclient -L ip_addr/hostname show remote shares of a windows host 
smbget -Rr smb://ip_addr/share like wget can download files from a host windows via smb 
mount -t smbfs -o username=user,password=pass //WinClient/share /mnt/share mount a windows network share

 

-b file            若文件存在且是一個塊特殊文件,則爲真
-c file            若文件存在且是一個字符特殊文件,則爲真
-d file            若文件存在且是一個目錄,則爲真
-e file            若文件存在,則爲真
-f file            若文件存在且是一個規則文件,則爲真
-g file            若文件存在且設置了SGID位的值,則爲真
-h file            若文件存在且爲一個符合鏈接,則爲真
-k file            若文件存在且設置了"sticky"位的值
-p file            若文件存在且爲一已命名管道,則爲真
-r file            若文件存在且可讀,則爲真
-s file            若文件存在且其大小大於零,則爲真
-u file            若文件存在且設置了SUID位,則爲真
-w file            若文件存在且可寫,則爲真
-x file            若文件存在且可執行,則爲真
-o file            若文件存在且被有效用戶ID所擁有,則爲真

-z string          若string長度爲0,則爲真
-n string          若string長度不爲0,則爲真
string1 = string2  若兩個字符串相等,則爲真
string1 != string2 若兩個字符串不相等,則爲真

int1 -eq int2      若int1等於int2,則爲真
int1 -ne int2      若int1不等於int2,則爲真
int1 -lt int2      若int1小於int2,則爲真
int1 -le int2      若int1小於等於int2,則爲真
int1 -gt int2      若int1大於int2,則爲真
int1 -ge int2      若int1大於等於int2,則爲真

!expr              若expr爲假則複合表達式爲真。expr可以是任何有效的測試表達式
expr1 -a expr2     若expr1和expr2都爲真則整式爲真
expr1 -o expr2     若expr1和expr2有一個爲真則整式爲真

特殊變量

$0                 正在被執行命令的名字。對於shell腳本而言,這是被激活命令的路徑
$n                 該變量與腳本被激活時所帶的參數相對應。n是正整數,與參數位置相對應($1,$2…)
$#                 提供腳本的參數號
$*                 所有這些參數都被雙引號引住。若一個腳本接收兩個參數,$*等於$1$2
$@                 所有這些參數都分別被雙引號引住。若一個腳本接收到兩個參數,$@等價於$1$2
$?                 前一個命令執行後的退出狀態
$$                 當前shell的進程號。對於shell腳本,這是其正在執行時的進程ID
$!                 前一個後臺命令的進程號

 

 

二三、Shell編程相關

 

①、內置變量

1、declare

declare聲明變量的使用,總結如下:
declare [+/-][選項] 變量名
選項:
   -:給變量添加類型屬性
   +:取消變量的類型屬性
  -a:將變量聲明爲數組型,-A將聲明一個關聯數組,俗稱字典。  關聯知識:Shell 數組與關聯數組詳解及實例代碼(https://www.jb51.net/article/103915.htm
  -i:將變量聲明爲整型
  -x:將變量聲明爲環境變量
  -r:將變量聲明爲只讀變量
  -p:查看變量的被聲明的類型

declare -i 說明:

和 (())、let、$[] 不同,declare -i的功能非常有限,僅支持最基本的數學運算(加減乘除和取餘),不支持邏輯運算(比較運算、與運算、或運算、非運算),所以在實際開發中很少使用。

declare -i m n ret
m=10
n=30

ret=$m+$n
echo $ret

ret=$n/$m
echo $ret

declare的作用域,只在函數內,出來後就失效了,如下:

#!/bin/bash

foo()
{
declare FOO="bar"
}

bar()
{
foo
echo $FOO
}

bar


 

②、數據結構

 

1、數組

 

Linux shell中數組的使用

數組有兩種數據類型:

A). 一是數值類型;

B). 二是字符串類型.

雖然shell本身是弱類型的,但也可以這麼區分。

數值類型的數組:一對括號表示數組,數組中元素之間使用“空格”來隔開。

  舉個列子: 

  arr_number=(1 2 3 4 5);

字符串類型數組:同樣,使用一對括號表示數組,其中數組中的元素使用雙引號或者單引號包含,同樣使用“空格”來隔開。

  arr_string=("abc" "edf" "sss"); 或者 arr_string=('abc' 'edf' 'sss');

#!/bin/bash
arr_number=(1 2 3 4 5)

# ①、獲取數組長度
# 語法: ${#ARRAY_NAME[@|*]}
echo 'arr_number length ='${#arr_number[@]}
echo 'arr_number length ='${#arr_number[*]}

# ②、根據下標訪問數組元素(注意:下標與java語法類似,從0開始)
# 2nd key's value
echo "2nd key's value ="${arr_number[1]}

# ③、分片訪問
echo ${arr_number[@]:0:6}

# ④、模式替換
echo ${arr_number[@]/3/33}

# ⑤、數組的遍歷
for e in ${arr_number[@]}
do
        echo $e
done

# ⑥、綜合案例
# 編注:數組默認分割符爲空格,如果數組元素中本身包含空格,也會被截斷,這裏通過改變IFS(系統字段分割# 符默認爲空格)爲換行,達到分割數組的目的。
greet=('hello world' "hi,john")
OLD_IFS=$IFS
IFS='\n'
for e in ${greet[@]}
do
        echo $e
done
IFS=$OLD_IFS

 

2、字典dict 或 Map

 

1). 聲明字典類型:
declare -A dic

這裏一定要-A來聲明,-a只能用來聲明數組類型。

2). 字典賦初值
dic=([key1]="value1" [key2]="value2" [key3]="value3")

3). 字典動態賦值
dic['key']=value

4). 打印指定key的value
echo ${dic['key']}

5). 打印所有key值
echo ${!dic[*]}

6). 打印所有value
echo ${dic[*]}

7). 遍歷key值
for key in $(echo ${!dic[*]})
do
    echo "$key : ${dic[$key]}"
done
8). 綜合案例

#! /bin/sh
#輸入格式爲一行一個單詞

declare -A dict
dict=([k1]="v1" [k2]="v2")
echo ${dict["k1"]}
echo ${!dict[*]}
echo ${dict[*]}

for key in ${!dict[*]}
do
        echo "$key : ${dict[$key]}"
done
set -x
aa="null"
bb=
cc=''

#    -z 字符串爲"null".就是長度爲0.
#
#    -n 字符串不爲"null"
#
#     注意:
#
#     使用-n在[]結構中測試必須要用""把變量引起來.使用一個未被""的字符串來使用! -z
#
#     或者就是未用""引用的字符串本身,放到[]結構中。雖然一般情況下可
#
#     以工作,但這是不安全的.習慣於使用""來測試字符串是一種好習慣.
if [ -n "$cc" ];then
        echo "aa is not null"
fi
set +x


#定義字典類型變量
declare -A dict

#從標準輸入讀取
while read word
do
    #若key爲word的變量不存在,則爲未定義,即第一次遇到此word,則將此word加入字典並設置其value爲1。,否則自增value值
    if [ ! -n dict[${word}] ];then
        dict[${word}]=1
    else
        ((dict[${word}]++))
    fi
done
#打印統計結果
echo -e "word\t\tcount"
for key in $(echo ${!dict[*]})
do
    echo -e "$key\t\t${dict[$key]}"
done

綜合案例二: shell的map簡單的添加、查找、刪除、遍歷

 

3、管道輸出中執行下一條指令

ps -ef | grep 'new-consumer' | awk '{print $2}' |xargs kill -9       #刪除kafka consumer進程

ps -ef|grep java|grep -v grep|awk '{print $2}'|xargs kill -9          #刪除java進程   

find /opt/flume-custom/ -name *.conf|xargs grep -re "127.0.0.1:9092" #查找到的文件中查找指定字符串

find /opt/ -type f -name '*.log' |xargs grep 'db.hostname'

cat ~/.ssh/id_rsa.pub | ssh [email protected] "cat - >> ~/.ssh/authorized_keys"

kill -9 $(ps -ef|grep "sh\ *start_new.sh\ *main"|grep -v grep|awk '{print $2}') #\ *表任意多空格

kill -9 `ps -ef|grep data-integration|awk '{print $2}'`

ls|while read f;do zip -r ${f}.zip $f;done  #壓縮所有ls出來的文件夾

 

讀取文件每一行,並循環做處理:

①、while read line
do
       …
done < file

②、cat file  | ${BIZ_LOGICAL}

 

綜合實例:

ssh   127.0.0.1 <<EOF
sudo su
sed -i 's/^Hostname=.*/Hostname=127.0.0.1/' /etc/zabbix/zabbix_agentd.conf
cat /etc/zabbix/zabbix_agentd.conf | grep Hostname
ps -ef | grep zabbix | awk  '{print \$2}' | xargs kill -9 
/usr/sbin/zabbix_agentd -c /etc/zabbix/zabbix_agentd.conf
sleep 2
ps -ef  | grep zabbix
exit
exit
EOF

 

4、循環、迭代邏輯控制

 

4.1 while循環語法(while...do...done)

#hdfs文件統計

hdfs dfs -ls /  | hdfs dfs -ls `awk '{print $8}'`/ |  echo -e "`awk '{print $8}'`/ \n"  | while read line ; do echo -e "$line \t\t\t\t\t `sudo -u hdfs hdfs dfs -ls -R $line | wc -l `"    ;done

hdfs dfs -ls /  | hdfs dfs -ls `awk '{print $8}'`/ |  awk '{ cmd="echo -e  "$8"\\\t\\\t\\\t\\\t`sudo -u hdfs  hdfs dfs -ls -R  "$8"| wc -l`" ;cmd|getline ; print $0}'

#jar包裏統計包含指定字符的文件名

ls;while read line;do cat /dev/null>$line; done

ls lib/* |while read line;do jar -tf $line|grep LogAnalysis; echo $line;done

#hdfs文件大小統計排序

hdfs dfs -du ${HDFS_PATH} | sort -rn | head -n 10 | awk '{printf("%.2f\t\t%.2f\t\t%s\t\n",$1/1024/1024/1024,"\t"$2/1024/1024/1024,"\t"$3)}'

#獲取所有java程序的進程號

ps -ef | while read line ; do if [[ $line =~ "java" ]] ;then echo $line |  awk -F ' ' '{print $2}' ; fi ;done

//循環所有文件,並添加header
#!/bin/bash
ls OrderDetail_sysdate_* |while read file;do
sed -i "1i\\$(cat header.csv)" $file
done

 

綜合案例:

清理日誌文件夾中的日誌文件,將其置爲黑洞文件內容(即情況該文件)。

#!/bin/bash

#先遍歷本文件夾裏文件夾
dir_list=`ls`

#對查詢到的文件夾執行清空其內文件的操作
for dir in $dir_list;do
    echo $dir
    ls $dir/* | while read line;do echo $line; cat /dev/null > $line; done
done

for i in `seq 1 $(cat /proc/cpuinfo |grep "physical id" |wc -l)`; do dd if=/dev/zero of=/dev/null & done

pkill -9 dd

 

5、break 與 contine區別

如下代碼所示:

不帶參數 N:  
break  循環只能退出最內層的循環;
continue  只能去掉本次循環的剩餘代碼;

 

帶參數 N:  
break N 可以退出N層循環;
continue N  將會把N層循環剩餘代碼都去掉,單循環次數不變;
#!/bin/bash

for i in a b c d
do
    echo -n $i

    for j in `seq 10`
    do
        if test $j -eq 5;then
            #break
           # continue
            #break 2
            continue 2
        fi
        echo -n $j
    done

    #換行
    echo 
done

##########################################
###
### Program result:
###
##########################################
#
#>>>>>>>>>>>>>> 1. break >>>>>>>>>>>>>>>>>
# a1234
# b1234
# c1234
# d1234

#>>>>>>>>>>>>>> 2. continue >>>>>>>>>>>>>>>>>
# a1234678910
# b1234678910
# c1234678910
# d1234678910

#>>>>>>>>>>>>>> 3. "break 2","break 3" has same effect >>>>>>>>>>>>>>>>>
# a1234

#>>>>>>>>>>>>>> 4. "continue 2" >>>>>>>>>>>>>>>>>
# a1234
# b1234
# c1234
# d1234

 

6、大文件拆分處理

 

文件拆分:

split -d -a 8 -l 10000 PayOrderDetail.csv PayOrderDetail_sysdate_.csv

 

7、awk

#批量刪除hdfs下ods層下所有數據

hdfs dfs -lsr /user/hive/warehouse/ods|awk '{print "hdfs dfs -rm -R" $8}'

 

 

 

參考博文列表:

  1. https://www.cnblogs.com/yjd_hycf_space/p/7730690.html
  2. https://www.cnblogs.com/zhaihongliangblogger/p/6286773.html
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章