Now we know how to navigate around our system, let’s interact with some files:

Normally is good to have filenames with extension, but sometime that is not the case on linux/Unix/Unix-like systems,

To figure out what type of file it is:

file <filename>

Copying files

to copy some files:

cp [options] <source files> <destination>

it support wildcards for file names, such as:

# this will copy every file with name starts with "image"
# and extension of ".jpg" to the Downloads folder
cp image*.jpg ~/Downloads
  • to prompt you when copying over existing files, use -i the interative option, I recommend adding it when copying multiple files

    cp -i ./old-workspace/* ./new-workspace/
    
  • to forcefully overwrite existing files

    cp -f ./patch-files/* ./broken-mess/
    
  • to create backups of source files

    cp -fb ./updates/* ./old-build/
    
  • to copy multiple files, and files of subdirectories

    cp -r ./notes/ /mnt/backupdisk/
    

Moving and Renaming Files

The mv command has similar parameter to cp command:

mv [options] <source files> <destination>

In linux/unix/unix-like systems, mv is also used for renaming files

mv <orginal_filename> <new_filename>

Directories

To make a new directory:

mkdir <new directory pathname>
  • if you are creating a subdirectory of a directory that doesn’t exist yet, use the -p parents flag to create them automatically

    mkdir -p ~/fridge/drinks/
    

Similarily, to remove a directory

rmdir <directory pathname>

Note: directory should be empty, else is better to use the rm -r command


Viewing Files

cat

To concatenate file (think of it as grabing the contents of the file for now), and print to standard output (will explain standard I/O stream later)

cat [options] <filenames>
  • to number all the lines

    cat -n my_codes.c
    

alternative to cat:

the opposite of cat is tac, which will function the same but reversed, print from the end to the beginning

less and more

sometime cating a file is not a good option, files such as logs are way too long, another option would be

less system.log

less is more, which is ironic, because less shows file line by line that you can scroll through.

more errors.log

but the more command will show by pages(how ever many can fit on screen at once)

heads or tails

These are less useful, but still good to know.

To show the beginning of a file (default 10 lines):

head doc.md
  • to specify exactly how many lines to show, use the lines option

    head -n 3 letter.txt
    

The opposite command is tail, which shows the last part of a file (default 10 lines):

tail recipt.txt
  • to follow the file as it grows with new contents added

    tail -f activities.log