Linux Commands - Deleting Files and Directories (part 2)
More on Deleting Subdirectories
Recall you can only delete a directory if it is empty,
$ rmdir cse220
rmdir: `cse220': Directory not empty
To delete all the files in a subdirectory and all of its subdirectories and then delete the subdirectory itself, use the -r (recursive) command option with the rm command,
$ rm -r cse220
$ ls cse220
ls: cannot access cse220: No such file or directory
This deletes the cse220 directory and all its contents.
The following is a very dangerous command(recall * is a wildcard, referring to 0 or more characters),
$ cd
$ pwd
/home/fredf
$ rm -rf *
$ ls
Remember, the * in the rm command refers to all files/directories in the current directory. So this command deletes everything in your home directory (all files, all directories, all subdirectories, and all files in all subdirectories). The option –f means force and will cause even files marked as read-only to be deleted(if you own them).
Copying Files and Directories
To copy a file use the cp command
cp fileSRC fileDest
Examples
To create a copy of file1.c, named file1.c.backup,
$ cd
$ cp file1.c file1.c.backup
$ ls
a.out file1.c file1.c.backup file3 src
Copy a file to another directory
$
mkdir cse220
$ cp file3 cse220
$ ls cse220
file3
Copy a file to the parent directory,
$cp file3 ..
$ls ..
file3
To copy all the .c files from one directory to another,
$ mkdir src-backup
$ cp *.c src-backup
$ ls src-backup
file01.c file02.c file03.c file01.o file02.o file03.o
Recursive Option (-r)
To copy all the files in a directory (and its subdirectories) to another directory, use the -r command line option with cp (-r stands for recursive),
$ cd
$ cp -r src src-backup
$ ls src-backup
file01.c file02.c file03.c file01.o file02.o file03.o
To copy a file from another directory to the current directory,
$ cp ../dir/file .
Note: The . is necessary in the command to specify the destination for the file that is being copied. Without it you will get an error message,
$ cp ../dir/file
cp: missing destination file operand after `/dir/file'
Try `cp --help' for more information.
Moving and Renaming Files
To move a file from one location to another use the mv (move) command. Note that move is different from copy in that copy "makes a copy" so the original file remains where it was at. Move actually "moves the file" from one place to another, so the original is removed. 'mv' can also be used with the recursive option -r.
mv fileSRC fileDest
Examples
$ cd
$ ls
a.out file1.c file3 src
$ mv file1.c src
$ ls
a.out file3 src
$ ls src
file01.c file02.c file03.c file01.o file02.o file03.o file1.c
$ mv src/file1.c ../../tmp
$ ls src
file01.c file02.c file03.c file01.o file02.o file03.o
To rename a file in *nix you move it to a new file, e.g., to rename file1.c to file01.c,
$ mv file1.c file01.c
Previous - File Name Globbing with *, ?, [ ] | Previous - Viewing Files with Cat and Less
No comments:
Post a Comment