与在Windows下一样,Linux下也经常需要对文件进行复制、删除、改名等操作,这些操作都可以通过命令来完成。首先,我们来学习Linux复制文件的命令,cp,即英文copy的缩写。
复制文件或目录
cp [option] source destination
-i 如果目的文件已存在,提示是否覆盖 -n 不覆盖已存在的文件 -r/R 复制目录
cp后面至少需跟两个参数,根据参数是文件还是目录,cp的用法可以分为几种情况:
1. 两个参数都是文件,在同一目录下,文件名不同:
[peter@ibi98 ~]$ ls at_LEC1_protein.fa file1 file2 flower hello.sh lily prac test test_eof [peter@ibi98 ~]$ cp file1 file3 [peter@ibi98 ~]$ ls at_LEC1_protein.fa file1 file2 file3 flower hello.sh lily prac test test_eof
2. 两个参数都是文件,在不同目录下,文件名不同:
[peter@ibi98 ~]$ ls prac/ [peter@ibi98 ~]$ cp file1 prac/file3 [peter@ibi98 ~]$ ls prac/ file3
3. 第一个参数是文件,第二个参数是目录(相当于两个参数都是文件,在不同目录下,文件名相同):
[peter@ibi98 ~]$ cp file1 prac/ [peter@ibi98 ~]$ ls prac/ file1 file3
4. 第一个参数是目录,第二个参数是已存在的目录,运行命令后,把第一个目录复制到第二个目录中(需要 -r 选项):
[peter@ibi98 ~]$ ls at_LEC1_protein.fa file1 file2 file3 flower hello.sh lily prac test test_eof [peter@ibi98 ~]$ ls prac/ file1 file3 [peter@ibi98 ~]$ cp -r flower/ prac/ [peter@ibi98 ~]$ ls prac/ file1 file3 flower
5. 第一个参数是目录,第二个参数是一个不存在的目录,运行命令后,把第一个目录复制成第二个目录(需要 -r 选项):
[peter@ibi98 ~]$ ls at_LEC1_protein.fa file1 file2 file3 flower hello.sh lily prac test test_eof [peter@ibi98 ~]$ cp -r flower/ my_flower [peter@ibi98 ~]$ ls at_LEC1_protein.fa file1 file2 file3 flower hello.sh lily my_flower prac test test_eof [peter@ibi98 ~]$ ls prac/ file1 file3 flower [peter@ibi98 ~]$ cp -r flower/ prac/my_flower [peter@ibi98 ~]$ ls prac/ file1 file3 flower my_flower
6. 也可以把多个文件一起复制到一个目录中:
[peter@ibi98 ~]$ ls at_LEC1_protein.fa file1 file2 file3 flower hello.sh lily my_flower prac test test_eof [peter@ibi98 ~]$ ls prac/ file1 file3 flower my_flower [peter@ibi98 ~]$ cp file2 hello.sh prac/ [peter@ibi98 ~]$ ls prac/ file1 file2 file3 flower hello.sh my_flower
或者把多个文件或目录一起复制到一个目录中:
[peter@ibi98 ~]$ ls at_LEC1_protein.fa file1 file2 file3 flower hello.sh lily my_flower prac test [peter@ibi98 ~]$ mkdir fruit [peter@ibi98 ~]$ ls at_LEC1_protein.fa file1 file2 file3 flower fruit hello.sh lily my_flower prac test test_eof [peter@ibi98 ~]$ ls prac/ file1 file2 file3 flower hello.sh my_flower [peter@ibi98 ~]$ cp -r at_LEC1_protein.fa fruit/ prac/ [peter@ibi98 ~]$ ls prac/ at_LEC1_protein.fa file1 file2 file3 flower fruit hello.sh my_flower
复制多个文件或目录的时候,最后一个参数需要是目录。
用cp复制文件时,相对路径和绝对路径都是可以的。