Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

Linux 基礎常用命令(三):cp、mv 與文本處理工具

cp:複製檔案

把 test 複製到 y 目錄並保持原名:

[root@iZ28g26851kZ x]# cp test y
[root@iZ28g26851kZ x]# tree
./
├── test
├── y
│   └── test
└── z
    └── k

複製並改名為 test.txt:

[root@iZ28g26851kZ x]# cp test y/test.txt

一次複製多個檔案到別的目錄:

[root@iZ28g26851kZ x]# cp y/test y/test.txt z/

-r:遞迴複製目錄

[root@iZ28g26851kZ x]# cp -r y z

-p:保留檔案屬性

先看看不加 -p 的情況(先切換成其他使用者再執行 cp):

[root@iZ28g26851kZ www]# ls -l
-rw-rw-r-- 1 www www 0 May  4 15:16 txt1
[root@iZ28g26851kZ www]# cp txt1 txt2
[root@iZ28g26851kZ www]# ls -l
-rw-rw-r-- 1 www  www 0 May  4 15:16 txt1
-rw-r--r-- 1 root root 0 May  4 15:18 txt2

檔案複製成功,但擁有者從 www 變成了執行命令的 root。加上 -p 後:

[root@iZ28g26851kZ www]# cp -p txt1 txt3
[root@iZ28g26851kZ www]# ls -l
-rw-rw-r-- 1 www  www 0 May  4 15:16 txt1
-rw-r--r-- 1 root root 0 May  4 15:18 txt2
-rw-rw-r-- 1 www  www 0 May  4 15:16 txt3

屬性完整保留了下來。

-a:歸檔複製

常用於備份,會保存檔案的一切屬性。

mv:移動與重新命名

[root@iZ28g26851kZ x]# mv y/ z
[root@iZ28g26851kZ x]# tree
.
└── z
    └── y
        ├── test
        └── test.txt
[root@iZ28g26851kZ y]# mv test test2
[root@iZ28g26851kZ y]# ll
-rw-r--r-- 1 root root 9 May  4 14:43 test2
-rw-r--r-- 1 root root 9 May  4 14:47 test.txt

查看檔案內容

常見工具有 cat、more、less、head、tail。

tail

預設顯示檔案最後 10 行。-f 會持續監看檔尾而不退出,其他進程寫入時即時印出,最常用來追 log。

cut:按列擷取

[root@iZ28g26851kZ opt]# cut -d: -f1 /etc/passwd
root
bin
daemon
...
www

-d 指定分隔字元(這裡用冒號),-f 指定要顯示第幾欄。同時顯示第一、三欄:

[root@iZ28g26851kZ opt]# cut -d: -f1,3 /etc/passwd
root:0
bin:1
www:501

顯示一到三欄:

[root@iZ28g26851kZ opt]# cut -d: -f1-3 /etc/passwd
root:x:0
www:x:501

sort:排序

-n 數值排序    -r 降序      -t 指定欄分隔符
-k 指定關鍵字欄 -u 相同行只顯示一次   -f 忽略大小寫

以 /etc/passwd 第三欄做數值降序:

[root@iZ28g26851kZ opt]# sort -t: -k3 -r -n /etc/passwd
www:x:501:501::/home/www:/bin/bash
mysql:x:500:500::/home/mysql:/bin/bash
...
root:x:0:0:root:/root:/bin/bash

uniq

-c 顯示重複次數;-d 只顯示重複的行。

wc:文本統計

[root@iZ28g26851kZ opt]# wc test
82  78  610 test

分別是 82 行、78 個單詞、610 位元組。

tr:字元處理

刪除指定字元集合中的所有字元:

[root@iZ28g26851kZ opt]# tr -d w
asdaswwwwwwwwwwwasdasd
asdasasdasd

字元替換:

[root@iZ28g26851kZ opt]# tr a b
aaaaaaccccccccccdddddddd
bbbbbccccccccccdddddddd

alias 與 unalias

語法:alias CMDALIAS='COMMAND [options] [arguments]'

[root@iZ28g26851kZ ~]# alias list='ls -l'
[root@iZ28g26851kZ ~]# list
libiconv-1.14  libiconv-1.14.tar.gz  mysql-5.1.51  nginx-1.8.0 ...

別名只在當前 shell 生命週期內有效。不帶參數執行 alias 可列出目前所有別名:

[root@iZ28g26851kZ ~]# alias
alias cp='cp -i'
alias l.='ls -d .* --color=auto'
alias ll='ls -l --color=auto'
alias ls='ls --color=auto'
alias mv='mv -i'
alias rm='rm -i'

取消別名:

[root@iZ28g26851kZ ~]# unalias list
[root@iZ28g26851kZ ~]# list
-bash: list: command not found
Copyright © Linux教程網 All Rights Reserved