Manipulating Files

In addition to creating files and directories, we can manipulate files and directories.

Inspecting files

We can use less to visualise a text file

[user@host animals]$ less birds.txt

When using less:

We can also search files:

[user@host animals]$ grep bat mammals.txt
whiskered bat, myotis mystacinus
natterer's bat, myotis nattereri
daubenton's bat, myotis daubentonii
leisler's bat, nyctalus leisleri
brown long-eared bat, plecotus auritus

You will learn about grep in the Module Finding Things.

Other file inspection tools

Command Action
head visualise the first 10 lines of a file
tail visualise the last 10 lines of a file
cat print file contents to the terminal screen
sdiff visualise and compare two files side-by-side

Copying files and directories

To copy a file we use the cp command:

[user@host ~]$ cp a_file copy_of_a_file
[user@host ~]$ ls
a_directory  a_script.sh  bread  cakes.sh     copy_of_a_file  Scratch
a_file       b_directory  cake   c_directory  new_directory   shell-training

 Moving/Renaming files and directories

The command mv can be used to rename or move a file or directory.

[user@host ~]$ mv a_file control.in
[user@host ~]$ ls
a_directory  b_directory  cake      c_directory  copy_of_a_file  Scratch
a_script.sh  bread        cakes.sh  control.in   new_directory   shell-training
[user@host ~]$ mv control.in a_directory
[user@host ~]$ ls a_directory
control.in

In this example we initial rename ‘a_file’ as ‘control.in’, this file is then moved to the directory ‘a_directory’.

It is possible to move and rename a file with one command, e.g.:

mv a_file a_directory/control.in

Deleting files and directories

Unlike deleting files on other operating systems, a delete is permanent and cannot be undone.

[user@host ~]$ rm a_directory/control.in
[user@host ~]$ rm a_directory
rm: cannot remove ‘a_directory/’: Is a directory
[user@host ~]$ rm -r a_directory
[user@host ~]$

To delete files and directories we use the following commands:

rm will not let you delete directories by default, this is why we use the recursive option (-r) to make it apply to all of its contents including sub-directories. Because a lot can go wrong with this command the -i option is recommended as it will prompt for confirmation for each file deleted.

Next activity: Exercises - Creating directories.