Redirecting Input and Output Flashcards
What is stdin?
Standard input is information inputted into the terminal through the keyboard or input device.
What is stdout?
Is information outputted after a process is run.
stderr?
Is an error message outputted by a failed process.
Explain the following command:
$ echo “Hello” > hello.txt
The string “Hello” is entered as stdin. The ‘>’ command redirects the stdout to a file named hello.txt.
Note that ‘>’ will overwrite the contents of the hello.txt file if any exists.
Redirection;
What is the implication of using the “»” command?
It will redirect the stdout on the left of the command and appends it to the file on the right.
Explain the following command:
$ cat < deserts.txt
The input is reversed and the flows from right to left i.e.
deserts.txt is the input for the cat command.
What is the implication of using the “|” command?
the “pipe” command takes the standard output of a command on the left and pipes it in as the standard input for the command on the right. You can think of this as command to command redirection.
example:
cat volcanoes.txt | wc
$ sort
The sort command takes the lines of a file or standard input and orders it alphabetically for the standard output.
Note that the actual file does not change.
$ uniq
“unique” filters out adjacent duplicate lines in a file.
A common pattern when using the uniq command is to use the sort command first the pipe the output into uniq.
$ sort deserts.txt | uniq
$ grep
grep stands for “global regular expression print.” It searches files for lines that match a pattern and then prints the lines that contain a match.
It is case sensitive, to perform a case insensitive search use the -i option
$ grep -i America continents.txt
Note that the search term is not quoted.
-R stands for recursive it searches all files in a directory and out puts filenames and lines containing matched results.
-Rl searches all files in a directory and outputs only filenames with matched results (so no lines).
sed
sed stands for “stream editor”. It accepts standard input and modifies it based on an expression, before displaying it as output data.
Expression:
$ sed ‘s/snow/rain/’ forests.txt
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.
Importantly, the above command will only replace the first instance of “snow” on a line.
Expression:
$ sed ‘s/snow/rain/g’ forests.txt
The above command will replace snow with rain globally meaning all instances of snow on a line will be turned into rain.
Note however that only the command line output is modified the actual file is not changed.
Expression:
$ sed -i ‘s/snow/rain/g’ forests.txt
The above command will rewrite forests.txt and replace all instances of “snow” with “rain”.