These commands work on a Mac or a Linux. If you want to try them on Windows you could install Cygwin.
Command Line Magic
You will use the commands
The command ls
It gives you a list.
(From here on I assume you are already in a terminal ready to type in commands).
If you are in a directory and you type in
ls you will get a list of all directories and files.
You can type
ls -l and you will get the “long” version. You will get details of each file and directory.
You can also use the
ls with parameters.
It will output a list of all directories and files in your home folder under Documents.
The command >
You can use the
> command to add an input to an output.
You are at the supermarket. You get an empty basket. You go shopping around.
If you use the
> command it will be like:
You get something from the shelf and you put it into the basket.
If you use the
> command again it will be like:
Empty the basket and put in the new item.
> command, adds but it doesn’t append. It adds to the basket but replaces what was in the basket.
The command >>
>> to append an input to an output.
You can have a basket and every time you use the
>> append command you add to the basket but do not replace what was in the basket. Therefore, appends.
Using it for real now
Create a directory called groceries. Let’s say you are in your home folder Documents
$mkdir groceries $cd groceries
groceries directory add these files:
$touch pears-are-green.jpg $touch apples-are-red.jpg $touch pineapples-are-yellow.jpg
With the command
touch you can create files without having to open them.
Go back to the Command Line
Now it is time to use the magic.
$cd .. $ls groceries/ > list_of_groceries.txt
This will go over the directory
groceries get the name of every file and add it to the file
Now open that file to see if it worked.
Replace or Append?
Let’s say you create another directory called
$mkdir clothes $cd clothes
(Keep in mind where you are. Use the command
pwd to “print the working directory” otherwise you will get confused finding the files)
And you add some files to it
$touch tshirt.html $touch pants.mp4 $touch socks.markdown
You want to add this list of names to your
Let’s change the name of the file first.
$cd .. $mv list_of_groceries.txt list_of_things_to_buy.txt
If you use the
> add (replace) command you will replace the current list:
$ls clothes/ > list_of_things_to_buy.txt
If you open such file you will see only clothes, while the food is gone.
If you wanted to append and not replace you should do instead this.
Again, remember where you are with
Your working directory should be
Documents and you should have 2 directories (groceries, clothes) and 1 file (list_of_things_to_buy.txt)
$ls groceries/ > list_of_things_to_buy.txt $ls clothes/ >> list_of_things_to_buy.txt
Now you will have a list of all file names inside
You can apply these concepts for:
- Adding or appending data to a database
- Cleaning data
- Cleaning ginarmous excel files