0% found this document useful (0 votes)
14 views33 pages

Nota:: Usar o Q Command To Quit

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views33 pages

Nota:: Usar o Q Command To Quit

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

GIT

Git is a software that allows you to keep track of changes made to a


project over time. Git works by recording the changes you make
to a project, storing those changes, then allowing you to
reference them as needed.

Nota: Usar o q command to quit;

In scene-1.txt, add this text:

Harry Programmer and the Sorcerer’s Code: Scene 1

Then press enter to create a new empty line.

git init

Let’s turn the sorcerers-code directory into a Git project. We do this


with:

git init

The word init means initialize. The command sets up all the tools Git
needs to begin tracking changes made to the project.

Git Workflow

A Git project can be thought of as having three parts:

1. A Working Directory: where you’ll be doing all the work:


creating, editing, deleting and organizing files
2. A Staging Area: where you’ll list changes you make to the
working directory
3. A Repository: where Git permanently stores those changes as
different versions of the project

The Git workflow consists of editing files in the working


directory, adding files to the staging area, and saving
changes to a Git repository. In Git, we save changes with
a commit,
git status
As you write the screenplay, you will be changing the contents of the
working directory. You can check the status of those changes
with:

git status

git add

In order for Git to start tracking scene-1.txt, the file needs to be


added to the staging area.

We can add a file to the staging area with:

git add filename

The word filename here refers to the name of the file you are editing,
such as scene-1.txt.

Nota:
git add .
Adiciona todos os ficheiros do working directory.

git add filename_1 filename_2

Adiciona múltiplos ficheiros.

git diff
Imagine that we type another line in scene-1.txt. Since the file is
tracked, we can check the differences between the working directory
and the staging area with:

git diff filename

Notice the output:

 “Harry Programmer and the Sorcerer’s Code: Scene 1” is in the


staging area, as indicated in white.
 Changes to the file are marked with a + and are
indicated in green.

git commit

A commit is the last step in our Git workflow. A commit


permanently stores changes from the staging area inside the
repository.

git commitis the command we’ll do next. However, one more bit of
code is needed for a commit: the option -m followed by a message.
Here’s an example:

git commit -m "Complete first line of dialogue"

Standard Conventions for Commit Messages:

 Must be in quotation marks


 Written in the present tense
 Should be brief (50 characters or less) when using -m
git log

Often with Git, you’ll need to refer back to an earlier version of a


project. Commits are stored chronologically in the repository
and can be viewed with:

git log

In the output, notice:

 A 40-character code, called a SHA, that uniquely


identifies the commit. This appears in orange text.
 The commit author (you!)
 The date and time of the commit
 The commit message

-------------------------------------//----------------------------------------

Backtracking Intro

When working on a Git project, sometimes we make changes


that we want to get rid of.

Git offers a few eraser-like features that allow us to undo mistakes


during project creation.

head commit
In Git, the commit you are currently on is known as the HEAD commit.
In many cases, the most recently made commit is the HEAD commit.

To see the HEAD commit, enter:

git show HEAD

The output of this command will display everything the git log
command displays for the HEAD commit, plus all the file changes
that were committed.

Notice the output.

The ghost’s most recently added line is in green text.

git checkout
What if you decide to change the ghost’s line in the working directory,
but then decide you wanted to discard that change?

You could rewrite the line how it was originally, but what if you forgot
the exact wording? The command

git checkout HEAD filename

will restore the file in your working directory to look exactly as it did
when you last made a commit.

git reset I

What if, before you commit, you accidentally delete an important line
from scene-2.txt? Unthinkingly, you add scene-2.txt to the staging
area. The file change is unrelated to the Larry/Laertes swap and you
don’t want to include it in the commit.

We can unstage that file from the staging area using

git reset HEAD filename

This command resets the file in the staging area to be the


same as the HEAD commit.

It does not discard file changes from the working directory, it just
removes them from the staging area.

git reset II

Just like retracing your steps on that hike, Git enables you to rewind
to the part before you made the wrong turn. You can do this with:

git reset commit_SHA

This command works by using the first 7 characters of the


SHA of a previous commit. For example, if the SHA of the previous
commit is 5d692065cf51a2f50ea8e7b19b5a7ae512f633ba, use:

git reset 5d69206


HEAD is now set to that previous commit.

git reset review

To better understand git reset commit_SHA, notice the diagram on the


right. Each circle represents a commit.

Before reset:

 HEAD is at the most recent commit

After resetting:

 HEADgoes to a previously made commit of your choice


 The gray commits are no longer part of your project
 You have in essence rewound the project’s history
Let’s take a moment to review the new commands:

 git checkout HEAD filename: Discards changes in the


working directory.
 git reset HEAD filename: Unstages file changes in the
staging area.
 git reset commit_SHA: Resets to a previous commit in your
commit history.

-------------------------------------//----------------------------------------

GitHub
GitHub is both a website and a service that facilitates software
development by allowing you to store your code in containers,
called repositories, and by tracking changes made to your
code.
In addition, it offers a hosting service and tools to build, test, and
deploy code.
GitHub uses Git, a version-control development tool, to manage your
projects by tracking changes to files and allowing multiple people
to work on the same project.

1-2. Open the Start menu and search for the app, git bash.
3. Navigate to GitHub’s articles on setting up your Git
username and email and follow the instructions for each using Git Bash.

4. GitHub offers two authentication options, HTTPS and SSH, to keep


your work secure. This is a security measure that prevents anyone
who isn’t authorized from making changes to your GitHub repository.
In this article, we will use HTTPS. Navigate to GitHub’s article
on creating a personal access token and follow the instructions to configure
your computer to be able to use HTTPS.

NOTA: ABRIR HIPERLIGAÇOES ACIMA;


Try It Out!
Now you have everything you need to practice your Git skills on your
local computer. Take a moment to run the commands below to
initialize a Git repository. We will use this Git repository again later in
this tutorial so make sure you complete these steps exactly as
described.
1. mkdir git_practice to make a new directory to practice.
2. cd git_practice to make the new directory your working
directory.
3. git init to turn the current, empty directory into a fresh Git
repository.
4. echo "Hello Git and GitHub" >> README.txt to create a
new README file (more on this later) with some sample text.
5. git add README.txt to add the new file to the Git staging
area.
6. git commit -m "First commit" to make your first commit
with the new README file.

Your First Remote Repository on GitHub

Finally, we’ll create a repository on GitHub and then link it to a local


repository on your computer. This allows you to backup your work
constantly and safely, so you never need to worry about losing your
work again!

Now, let’s connect our local Git repository to GitHub.

Instructions
1. In your Command Line Interface, make sure your current working
directory is your new Git repository. Navigate there if not.

2. Check the status of which files and folders are new or have been
edited. There should be no files modified.

$ git status
3. On GitHub, create a new repository by clicking the New
repository button on the home page.

4. On the new repository page, give your repository a name. It’s not
necessary, but it would be convenient to name it the same as the
directory, git_practice. After naming the repository, click Create
repository.
5. After creating a repository, GitHub displays the repository page. At
the top of the page, make sure “HTTPS” is selected.

6.The repository is empty, so it’s time to connect it to your existing


work. Copy the Git commands on the GitHub page, under the title “…
or push an existing repository from the command line”, and paste
them into your Command Line Interface. Running these commands
will add a remote repository, and then push your local repository to
the remote repository.

When asked for a username and password, type in your GitHub


username and password and press enter after each. Don’t be
alarmed if you can’t see the characters you are typing, they are
intentionally hidden as a security measure.

7. Once your Command Line Interface reports that the push is


complete, refresh the page on GitHub. You should now see the text
you wrote earlier in the README file, “Hello Git and GitHub.”

GitHub automatically displays the contents of a file


named README.txt if it exists in the repository. The README file is the
perfect place to write a description of your project.

There you have it! Your first GitHub repository, linked to your local Git
repository. You’ve taken some huge leaps, so be proud! Now you can
use your knowledge of Git to track progress on your local computer
and push that progress to GitHub whenever you want.
Managing Branches
With Git, each teammate can create their own branch off of the main
project in order to work on bug-fixes, new features, experimental
code, etc.

By using separate branches, the main project remains intact and


unaffected before the changes are reviewed and merged into the
project.

Each repository can have one or more branches. The main branch —
the one where all changes eventually get merged back into, is
called main. The main branch is usually the working version of a
project and contains the production code, so it’s very
important to only merge clean and correct code into it!

When someone wants to create a new feature, fix a bug, or


just experiment, they should always create their own branch
with a descriptive name.

For example, the branch


name carlos_feature_dashboard_notifications includes the
author, branch type, and short branch description.

Creating a Pull Request

Pull Requests on GitHub allow collaborators to review and


give feedback on proposed code changes before they are
merged to the main branch. Through a process of discussion and
potentially some extra code changes, the pull request can be
ultimately approved, which means you can merge the changes into
the official project on the main branch.

When creating pull requests, it’s imperative that you include


as much relevant detail in the description as possible in order
to save review time. Add any comments or images that might
be useful for your reviewer.

Stick to smaller-sized pull requests since they’re easier and faster to


review.
Reviewing and Merging a Pull Request
The pull request should include a description and GitHub will
display all the files with the changes created. Each line of code
will have a clickable “+” button where you can add a comment in
regards to the line.

Here are few best practices when reviewing code:

 Don’t only comment on what should be changed, but why it


should be changed. Feel free to provide resources to make your
point.
 Be as clear as possible with your comments and make sure to
be clear as to what to modify.
 Look at the bigger picture and try to spot potential errors.

Once all the feedback is added, collaborators can click on “Submit


Review” and wait for a response. If all goes well, the pull request will
eventually be merged into main!

Deleting a Branch and Review


Once changes are merged, in order to keep things organized and
managed, it’s imperative to only keep active branches and
delete the closed ones.

-------------------------------------//----------------------------------------
GitHub and Markdown
With a little bit of Markdown magic, you can achieve text that includes headings,
hyperlinks, emojis, checkmarks,
You’ll learn the basics of Markdown and how to use it to write a good README for
your project!

-------------------------------------//----------------------------------------

Conventions of a Good README File

Your README file should be as good as your project itself.

Make your project stand out look professional by at least including the
following elements in your README:

 Project Title: the name of your project


 Description: This is an extremely important component of the
README. You should describe the main purpose of your project.
Answer questions like “why did you build this project?”
and “what problem(s) does it solve?”. It also helps to
include your motivations for the project and what you learned
from it.
 Features: If your project has multiple features, list them here.
You can even add screenshots and gifs to show off the features.
 How to use: Here, you should write step-by-step instructions
on how to install and use your project. Any software or package
requirements should also be listed here.
 Technologies: List all the technologies and/or frameworks you
used and what purpose they serve in your project.
 Collaborators: Write your team members’ or collaborators’
names here along with a link to their GitHub profile.
 License: It’s also important to list a license on your README so
other developers can understand what they can and cannot do
with your project. You can use this guide to help you choose a
license.

Keep README’s brief but detailed. README should always be


up-to-date and self-explanatory.

It can help your future self as well when you step away for a while and
need to get reacquainted with your project. Not to mention it’ll leave
a positive impression on future interviewers who look at your GitHub
profile.
-------------------------------------//----------------------------------------

GIT BRANCHING
git branch

Note: GitHub has changed the naming convention of the main branch
from master to main.

Git allows us to create branches to experiment with versions of a


project. Imagine you want to create version of a story with a happy
ending. You can create a new branch and make the happy ending
changes to that branch only. It will have no effect on the master branch
until you’re ready to merge the happy ending to the master branch.

You can use the command below to answer the question: “which
branch am I on?”

git branch

Note: In the output, the * (asterisk) is showing you what


branch you’re on.

branching overview

The diagram illustrates branching.

 The circles are commits, and together form the Git project’s
commit history.
 New Branch is a different version of the Git project. It
contains commits from the main branch but also has
commits that it does not have.
git branch 2

Right now, the Git project has only one branch: master.

To create a new branch, use:

git branch new_branch

Be sure to name your branch something that describes the purpose of


the branch. Also, branch names can’t contain whitespaces: new-
branch and new_branch are valid branch names, but new branch is
not.

git checkout

The master and fencing branches are identical: they share the same
exact commit history. You can switch to the new branch with

git checkout branch_name

Once you switch branches, you will now be able to make commits
on the branch that have no impact on master.

commit on a new branch


Congratulations! You have switched to a new branch. All the
commands you do on master, you can also do on this branch.

For example, to add files to the staging area, use:

git add filename


And to commit, use:

git commit -m "Commit message"


In a moment, you will make a commit on the fencing branch. On the
far right, the diagram shows what will happen to the Git project.

commit on a new branch


For example, to add files to the staging area, use:

git add filename


And to commit, use:

git commit -m "Commit message"


In a moment, you will make a commit on the fencing branch. On the
far right, the diagram shows what will happen to the Git project.

Notice the output:

 The commits you see were all made in


the master branch. fencing inherited them.
 This means that every
commit master has, fencing also has.

Note: if you find that your cursor is stuck in Git log, press q to
escape.
git merge

What if you wanted include all the changes made to


the fencing branch on the master branch? We can easily accomplish
this by merging the branch into master with:

git merge branch_name

Nota: Antes de fazer o merge, certificar-me que estou no


branch master/main para aplicar a operação.

merge conflict I

The merge was successful because master had not changed since we
made a commit on fencing. Git knew to simply update master with
changes on fencing.

What would happen if you made a commit on master before you


merged the two branches? Furthermore, what if the commit you
made on master altered the same exact text you worked on
in fencing? When you switch back to master and ask Git to merge the
two branches, Git doesn’t know which changes you want to keep.
This is called a merge conflict.

merge conflict II

Let’s say you decide you’d like to merge the changes


from fencing into master.

Here’s where the trouble begins!

You’ve made commits on separate branches that alter the same line
in conflicting ways. Now, when you try to merge fencing into master, Git
will not know which version of the file to keep.

We must fix the merge conflict.


In the code editor, look at resume.txt. Git uses markings to indicate
the HEAD (master) version of the file and the fencing version of
the file, like this:

<<<<<<< HEAD
master version of line
=======
fencing version of line
>>>>>>> fencing

EXERCICIO:

Note: If the markings are not showing in resume.txt, please


close resume.txt and re-open via the folder icon at the top left
corner of the editor.

Git asks us which version of the file to keep: the version


on master or the version on fencing. You decide you want
the fencing version.

From the code editor:

Delete the content of the line as it appears in the master branch


Delete all of Git’s special markings including the
words HEAD and fencing. If any of Git’s markings remain, for
example, >>>>>>> and =======, the conflict remains.

delete branch

In Git, branches are usually a means to an end. You create them to


work on a new project feature, but the end goal is to merge that
feature into the master branch. After the branch has been
integrated into master, it has served its purpose and can be
deleted.

The command

git branch -d branch_name


will delete the specified branch from your Git project.

Now that master contains all the file changes that were in fencing, let’s
delete fencing.

You’ll need the -D option, because these feature branches were


never merged into master:

git branch -D branchname

-------------------------------------//----------------------------------------

GIT TEAMWORK

Git also offers a suite of collaboration tools to make working with


others on a project easier.

Imagine that you’re a science teacher, developing some quizzes with


Sally, another teacher in the school. You are using Git to manage the
project.

In order to collaborate, you and Sally need:


 A complete replica of the project on your own computers
 A way to keep track of and review each other’s work
 Access to a definitive project version

You can accomplish all of this by using remotes. A remote is a


shared Git repository that allows multiple collaborators to
work on the same Git project from different locations.
Collaborators work on the project independently, and merge changes
together when they are ready to do so.

git clone

Sally has created the remote repository, science-quizzes in the directory curriculum,
which teachers on the school’s shared network have access to. In order to get your
own replica of science-quizzes, you’ll need to clone it with:

git clone remote_location clone_name

In this command:

 remote_location tells Git where to go to find the remote. This could be a web
address, or a filepath, such as:

/Users/teachers/Documents/some-remote

 clone_name is the name you give to the directory in which Git will clone the
repository.

EXERCICIO:

git clone /home/ccuser/workspace/curriculum/science-quizzes my-


quizzes

OU

git clone science-quizzes my-quizzes

git remote –v

One thing that Git does behind the scenes when you clone science-
quizzes is give the remote address the name origin, so that you can
refer to it more conveniently. In this case, Sally’s remote is origin.

You can see a list of a Git project’s remotes with the command:
git remote -v
Notice the output:
origin /home/ccuser/workspace/curriculum/science-
quizzes (fetch)
origin /home/ccuser/workspace/curriculum/science-
quizzes (push)

 Git lists the name of the remote, origin, as well as its location.
 Git automatically names this remote origin, because it refers
to the remote repository of origin. However, it is possible to
safely change its name.
 The remote is listed twice: once for (fetch) and once
for (push). We’ll learn about these later in the lesson.

git fetch

After you cloned science-quizzes, you had to run off to teach a


class. Now that you’re back at your computer, there’s a problem:
what if, while you were teaching, Sally changed the science-
quizzes Git project in some way. If so, your clone will no longer be
up-to-date.

An easy way to see if changes have been made to the remote


and bring the changes down to your local copy is with:

git fetch

This command will not merge changes from the remote into
your local repository. It brings those changes onto what’s
called a remote branch.

git merge

Even though Sally’s new commits have been fetched to your local
copy of the Git project, those commits are on the origin/master branch.
Your local master branch has not been updated yet, so you
can’t view or make changes to any of the work she has added.

The command will accomplish this for us.

git merge origin/master


Notice the output:

Updating a2ba090..bc87a1a
Fast-forward
biology.txt | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)

 Git has performed a “fast-forward” merge, bringing your


local master branch up to speed with Sally’s most recent
commit on the remote.

Git workflow

Now that you’ve merged origin/master into your local master branch,
you’re ready to contribute some work of your own. The workflow for
Git collaborations typically follows this order:

1. Fetch and merge changes from the remote


2. Create a branch to work on a new project feature
3. Develop the feature on your branch and commit your work
4. Fetch and merge from the remote again (in case new commits
were made while you were working)
5. Push your branch up to the remote for review

Steps 1 and 4 are a safeguard against merge conflicts


Step 5 involves git push, a command you will learn in the next
exercise.

git push

Now it’s time to share our work with Sally.

The command:

git push origin your_branch_name

will push your branch up to the remote, origin. From there, Sally
can review your branch and merge your work into
the master branch, making it part of the definitive project version.

In the output, notice the line:


To /home/ccuser/workspace/curriculum/science-quizzes
* [new branch] bio-questions -> bio-questions
Git informs us that the branch bio-questions was pushed up to the
remote

REVIEW:
We also learned the following commands

 git clone: Creates a local copy of a remote.


 git remote -v: Lists a Git project’s remotes.
 git fetch: Fetches work from the remote into the local copy.
 git merge origin/master: Merges origin/master into your
local branch.
 git push origin <branch_name>: Pushes a local branch to
the origin remote.

-------------------------------------//----------------------------------------

Deploying to GitHub Pages


Adding GitHub Pages Projects

You can set up your GitHub Pages to deploy every one of your
repositories in addition to <username>.github.io. This will allow you
to ensure all of your sites are deployed automatically whenever you
push to GitHub.
In GitHub, navigate to your <username>.github.io repository and
click Settings.

Within Settings, navigate to the Source section within the Github


Pages section. From the dropdown menu, select master branch and
then click Save.
Now, all of your repositories can be found
at http://<username>.github.io/<repository-name>. Try creating
a new repo with an HTML project inside it (perhaps push an old
project to GitHub) and then navigate to the deployed page.

-------------------------------------//----------------------------------------

Command Line
ls
In addition to -a, the ls command has several more options. Here are
three common ones:

 -a - lists all contents, including hidden files and directories


 -l - lists all contents of a directory in long format, as well as the
file permissions
 -t - orders files and directories by the time they were last
modified.

Cat

The cat command outputs the contents of a specified file. For


example:

cat action/superwoman.txt
will output all the text from superwoman.txt.
This is a useful command for peeking at files without opening them,
and confirming the result of other commands that change the
contents of files.

cp Part I

The cp command copies files or directories. Below, we copy the


contents of a source file into a destination file:

cp source.txt destination.txt
We could also copy a file to a destination directory:

cp source.txt destination/

cp Part II

To copy multiple files into a directory, use cp with a list of source files
as the first arguments, and the destination directory as the last
argument. Here, we copy the files file1.txt and file2.txt into the
same directory.

cp file1.txt file2.txt my_directory/

Wildcards

In addition to using exact filenames as arguments, we can use special


characters like * to select groups of files. These special characters are
called wildcards. For example, here we use cp to copy all files in
the current working directory into another directory.

cp * my_directory/

Here, w*.txt selects all files in the working directory starting with “w”
(prefix) and ending with “.txt” (suffix), and copies them
to my_directory/.

cp w*.txt my_directory/
mv

To move a file into a directory, use mv with the source file as the first
argument and the destination directory as the second argument. Here
we move my_file.txt into my_directory/.

mv my_file.txt my_directory/

To move multiple files into a directory, use mv with a list of source files
as the first arguments, and the destination directory as the last
argument. Here, we
move my_file_1.txt and my_file_2.txt into my_directory/.

mv my_file_1.txt my_file_2.txt my_directory/

To rename a file, use mv with the old file as the first argument
and the new file as the second argument. By
moving file_original.txt into file_renamed.txt, we rename the file
as file_renamed.txt.

mv file_origin.txt file_renamed.txt
rm

The rm command deletes files and directories. Here we remove the


file unwanted_file.txt from the filesystem.

rm unwanted_file.txt

The -r is an option that modifies the behavior of the rm command.


The -r stands for “recursive,” and it’s used to delete a directory and
all of its child directories.

rm -r unwanted_directory

Be careful when you use rm! It deletes files and directories


permanently. There isn’t an undelete command, so once you
delete a file or directory with rm, it’s gone.

REDIRECTION
$ echo "Hello" > hello.txt
The > command redirects the standard output to a file.
Here, "Hello" is entered as the standard input, and is then
redirected to the file hello.txt by > .

As a reminder, the cat command outputs the contents of a file to the


terminal. When you type:

$ cat hello.txt

the contents of hello.txt are displayed.

>

$ cat deserts.txt > forests.txt

> takes the standard output of the command on the left, and
redirects it to the file on the right. Here the standard output
of cat deserts.txt is redirected to forests.txt.

Note that > overwrites all original content in forests.txt. When


you view the output data by using cat on forests.txt, you will
see only the contents of deserts.txt.

>>
$ cat deserts.txt >> forests.txt

>> takes the standard output of the command on the left


and appends (adds) it to the file on the right.

Here, the output data of forests.txt will contain the original


contents of forests.txt with the content
of deserts.txt appended to it.

<
$ cat < deserts.txt

< takes the standard input from the file on the right and inputs it into
the program on the left. Here, deserts.txt is the standard input for
the cat command. The standard output appears in the terminal.

|
| is a “pipe.” The | takes the standard output of the command on the
left, and pipes it as standard input to the command on the right. You
can think of this as “command to command” redirection.

$ cat volcanoes.txt | wc

Above, the output of cat volcanoes.txt becomes the standard input


of wc. In turn, the wc, “word count”, command outputs the
number of lines, words, and characters in volcanoes.txt,
respectively.

$ cat volcanoes.txt | wc | cat > islands.txt

Multiple |s can be chained together. Here the standard output of cat


volcanoes.txt is “piped” to the wc command. The standard output
of wc is then “piped” to cat. Finally, the standard output of cat is
redirected to islands.txt.

You can view the output data of this chain by typing cat
islands.txt.

Sort

$ sort continents.txt
sort takes the standard input and orders it alphabetically for the
standard output (it doesn’t change the file itself). Here, the continents
in continents.txt will be listed in alphabetical order:

Africa
Antarctica
Asia
Australia
Europe
North America
South America

$ cat glaciers.txt | sort > sorted-glaciers.txt

Here, the command takes the standard output from cat


glaciers.txt and “pipes” it to sort. The standard output of sort is
redirected to a new file named sorted-glaciers.txt.
Uniq

$ uniq deserts.txt

uniq stands for “unique.” It filters out adjacent, duplicate lines in a


file. Here uniq deserts.txt filters out duplicates of "Sahara
Desert", because its duplicate directly follows the previous instance.
The “Kalahari Desert” duplicates are not adjacent, and thus remain.

$ sort deserts.txt | uniq


A more effective way to use uniq is to call sort to alphabetize a file,
and “pipe” the standard output to uniq. By piping sort
deserts.txt to uniq, all duplicate lines are alphabetized (and
thereby made adjacent) and filtered out.

sort deserts.txt | uniq > uniq-deserts.txt


Here we simply send filtered contents to uniq-deserts.txt, which
you can view with the cat command.

grep I

$ grep America continents.txt

grep stands for “global regular expression print.” It searches


files for lines that match a pattern and then returns the results. It is
also case sensitive. Above, grep searched for anything that
matched “America” in continents.txt.

$ grep -i America continents.txt


grep -i enables the command to be case insensitive.
Here, grep searched for capital or lowercase strings that match
“America” in continents.txt. Note that we don’t use quotes in
our command.

The above commands are a great way to get started with grep. If you
are familiar with regular expressions, you can also use regular
expressions to search for patterns in files.

grep II
$ grep -R Arctic /home/ccuser/workspace/geography

/home/ccuser/workspace/geography/deserts.txt:Arctic Desert
/home/ccuser/workspace/geography/oceans.txt:Arctic Ocean

grep -R searches all files in a directory and outputs filenames


and lines containing matched results. -R stands for
“recursive”. Above, grep -R searched
the /home/ccuser/workspace/geography directory for the string
“Arctic” and outputted filenames and lines with matching results.

$ grep -Rl Arctic /home/ccuser/workspace/geography

/home/ccuser/workspace/geography/deserts.txt
/home/ccuser/workspace/geography/oceans.txt

grep -Rl searches all files in a directory and outputs only


filenames with matched results (so no lines). l (a lowercase L,
not a capital i) stands for “files with matches.” Here grep -
Rl searched the /home/ccuser/workspace/geography directory for
the string “Arctic” and outputs filenames with matched results.

Sed

sed 's/snow/rain/' forests.txt

It is similar to “find and replace.”

Let’s look at the expression 's/snow/rain/':

 s: stands for “substitution.” It is always used when using sed for


substitution.
 snow: the search string, or the text to find.
 rain: the replacement string, or the text to add in place.

In this case, sed searches forests.txt for the word “snow” and
replaces it with “rain.” Importantly, the above command will
only replace the first instance of “snow” on a line.

sed 's/snow/rain/g' forests.txt

The above command uses the g expression, meaning “global.”


Here sed searches forests.txt for the word “snow” and
replaces it with “rain” globally. This means all instances of
“snow” on a line will be turned to “rain.”

sed as we’ve used it will only rewrite the command line output and
the actual file won’t be changed. In order to rewrite the actual
file, we need to use -i at the beginning of the command:

sed -i 's/snow/rain/g' forests.txt


The above command will rewrite forests.txt and
replace all instances (since we’re also using g) of “snow” with
“rain”.

You might also like