3. Pipelines and filters
-
Using the pipe operator "
|" (vertical bar), the standard output (stdout) of a command can be piped to the standard input (stdin) of another command. This is a powerful feature that allows us to perform complex operations on data by combining simple utilities. Let's see some examples:ls -l /usr/binls -l /usr/bin | less -
We can sort the data with
sort:ls /bin /usr/binls /bin /usr/bin | sort | less -
uniqcan omit or report repeated lines:ls /bin /usr/bin | sort | uniq | lessIf we want to see the list of duplicates instead we can use the option
-d:ls /bin /usr/bin | sort | uniq -d | less -
wccounts the lines, words, and bytes of the input:wc ls-output.txtcat ls-output.txt | wcIf we want it to show only the lines we can use the option
-l:ls /bin /usr/bin | sort | wc -lls /bin /usr/bin | sort -u | wc -lls /bin /usr/bin | sort | uniq -d | wc -l -
grepprints the lines that match a given pattern:ls /bin /usr/bin | sort -u | grep zipls /bin /usr/bin | sort -u | grep zip | wc -lThe option
-vshows the lines that do not match the pattern:ls /bin /usr/bin | sort -u | grep -v zipls /bin /usr/bin | sort -u | grep -v zip | wc -lThe option
-ican be used if we want grep to ignore case when searching (case in-sensitive search). -
head/tailprint the top or the last lines of input:ls /usr/bin > ls-output.txthead ls-output.txttail ls-output.txttail -n 5 ls-output.txttail -5 ls-output.txtls /usr/bin | head -n 5tail /var/log/dpkg.log -n 20tail /var/log/bootstrap.log -fThe option
-fmakes it follow the latest changes of the file in real time. Press "Ctrl-c" to terminate it. -
teesends its input both to stdout and to files:ls /usr/bin | tee ls.txt | grep zipls -l ls.txtless ls.txt