0% found this document useful (0 votes)
11 views17 pages

Cosc 224 Cat 1. Commands

The document outlines various UNIX commands and their functionalities, including AWK for data manipulation, GREP for searching text, and fmt for formatting text files. It also covers additional commands like basename, base32, base64, bash, bc, bg, bind, break, and builtin commands, providing syntax and examples for each. The information is structured to assist users in understanding and utilizing these commands effectively in a UNIX environment.

Uploaded by

allankimutai16
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)
11 views17 pages

Cosc 224 Cat 1. Commands

The document outlines various UNIX commands and their functionalities, including AWK for data manipulation, GREP for searching text, and fmt for formatting text files. It also covers additional commands like basename, base32, base64, bash, bc, bg, bind, break, and builtin commands, providing syntax and examples for each. The information is structured to assist users in understanding and utilizing these commands effectively in a UNIX environment.

Uploaded by

allankimutai16
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/ 17

GROUP 2:

UNIX COMMANDS
GROUP MEMBERS

1. Ronald Waweru EB1/66789/23


2. Morgan Moitalel EB1/68495/23
3. Joshua Malombe EB1/66805/23
4. Richard Makori EB1/66866/23
5. Margaret Ambari. EB1/66886/23
6. John Kariuki EB1/66841/23
7. Naom Mbenzi EB1/56059/21
8. Vincent Wambua EB1/66806/23
9. James Nyamai EB1/66904/23
10. Brandon Muriithi. EB1/61279/22
A. AWK Operations:
(a) Scans a file line by line
(b) Splits each input line into fields
(c) Compares input line/fields to pattern
(d) Performs action(s) on matched lines

Useful for:

(a) Transform data files


(b) Produce formatted reports

Programming Constructs:

(a) Format output lines


(b) Arithmetic and string operations
(c) Conditionals and loops

Syntax
awk options 'selection _criteria {action}' input-file > output-file
Awk is a scripting language used for manipulating data and generating reports. It searches one
or more files to see if they contain lines that matches with the specified patterns and then
perform the associated actions.
Examples
Default behavior of Awk: By default, Awk prints every line of data from the specified file.
$ awk '{print}' employee.txt
Output:
ajay manager account 45000 sunil
clerk account 25000 varun manager
sales 50000 amit manager account
47000 tarun peon sales 15000
Deepak clerk sales 23000 sunil
peon sales 13000 satvik director
purchase 80000
In the above example, no pattern is given. So the actions are applicable to all the lines. Action
print without any argument prints the whole line by default, so it prints all the lines of the file
without failure.

2. Print the lines which match the given


pattern.
$ awk '/manager/ {print}' employee.txt
Output:
ajay manager account 45000 varun
manager sales 50000 amit manager
account 47000
In the above example, the awk command prints all the line which matches with the ‘manager’.
3.Splitting a Line into Fields:
For each record i.e. line, the awk command splits the record delimited by whitespace character
by default and stores it in the $n variables. If the line has 4 words, it will be stored in $1, $2, $3
and $4 respectively. Also, $0 represents the whole line.
$ awk '{print $1, $4}' employee.txt
Output:
ajay 45000
sunil 25000
varun 50000
amit 47000
tarun 15000
Deepak 23000
sunil 13000
satvik 80000
In the above example, $1 and $4 represents Name and Salary fields respectively.
B. Syntax of GREP Command in Unix/Linux
The basic syntax of the grep command is as follows:
grep [options] pattern [files]
Here,
[options]: These are command-line flags that modify the behavior of grep.
[pattern]: This is the regular expression you want to search for.
[file]: This is the name of the file(s) you want to search within. You can specify multiple files for
simultaneous searching.
Options Available in grep Command

Options
Description
-c
This prints only a count of the lines that match a pattern
We can find the number of lines that matches the given string/pattern output
administrator@maggie- laptop: ~$ grep –c
–i
Ignores, case for matching.
The -i option enables to search for a string case insensitively in the given file. It matches the
words like “UNIX”, “Unix”, “unix”.
output
administrator@maggie-laptop: ~$ grep -i "unix" geekfile.txt Unix is great
-l
Displays list of a filenames only.
We can just display the files that contains the given string/pattern.
outadminstrator@maggie-laptop: ~$ grep -l "unix" * grep:
Desktop: is a directory grep: Documents: is a directory grep:
Downloads: is a directory

-n
Display the matched lines and their line numbers.
output
administrator@maggie-laptop: ~$ grep -n "unix" geekfile.txt 1: unix is
great os. unix was developed in bell labs.
4: unix is easy to learn. Unix is a multiuser os. learn unix. unix is a powerful.
administrator@maggie-laptop: ~$

-v
This prints out all the lines that do not matches the pattern

-e exp
Specifies expression with this option. Can use multiple times.

-f file
Takes patterns from file, one per line.

-E
Treats pattern as an extended regular expression (ERE)

-w
Match whole word output
administrator@maggie-laptop: ~$ grep -w "unix" geekfile.txt unix is great Os. unix
was developed in bell labs. unix is easy to learn. Unix is a multiuser os. learn unix.
unix is a powerful.
administrator@maggie-laptop: ~$

-o
Print only the matched parts of a matching line, with each such part on a separate output line.
Displaying only the matched pattern Using grep
By default, grep displays the entire line which has the matched string. We can make the grep to
display only the matched string by using the -o option.
C. fmt COMMAND

The fmt command in Linux/Unix is used to format text by adjusting line lengths to make it more
readable. Here's a detailed explanation, with examples:

FMT COMMAND

Function: The fmt command is used to format plain text by adjusting the width of lines to make
them more uniform. It's especially useful for reformatting paragraphs or text files into neat,
readable lines of a given length.

Syntax:

fmt [options] [file]

If you do not specify a file, fmt will read from the standard input (i.e., the terminal or a pipe).

Examples:
1. Basic Usage (Formatting Text) Command:
echo "This is a very long sentence that will be automatically wrapped at the default
width of 75 characters." | fmt Output:
This is a very long sentence that will be automatically wrapped at the default width of
75 characters.
Explanation: The sentence is automatically wrapped to fit within 75 characters per line, which is
the default width used by fmt.

2. Setting a Specific Line Width


Command:

echo "This is a very long sentence that will be automatically wrapped at the specified width of
40 characters." | fmt -w 40

Output:
This is a very long sentence that will be automatically
wrapped at the specified width of 40 characters.

Explanation: The -w option specifies the maximum width of the lines (in this case, 40
characters). The text is wrapped accordingly.

3. Formatting a Text File


Command:

fmt example.txt

Output: (Assuming example.txt contains multiple lines of text, fmt will format the text,
adjusting the line lengths for readability.)

Explanation: If the file example.txt contains multiple paragraphs, fmt will reformat the text to
have consistent line lengths.

4. Joining Short Lines into One Command:


echo -e "Line 1\nLine 2\nLine 3" | fmt
Output:
Line 1 Line 2 Line 3
Explanation: The fmt command will join short lines (e.g., lines shorter than the specified width)
into a single, longer line.

5. Using fmt with Input Redirection Command:


fmt < example.txt

Output: (Assuming example.txt contains long lines of text, the content will be formatted to
make lines more readable.)
Common Options for fmt
-w WIDTH
Set the width of the formatted lines. The default is 75 characters.
-c
Use the default width (75 characters), but leave blank lines between paragraphs.
-s
Do not break lines that are already shorter than the specified width.
-p
Don’t join lines unless necessary (useful for formatting text without merging short lines).

USES OF (b) INDEX OF THE LINUX COMMAND LINES: bash+ Utilities

1. Basename
The ‘basename’ command in Linux is a fundamental utility used in file manipulation and script
writing. It simplifies file paths by stripping directory information and optional suffixes from file
names.
Syntax of ‘basename’ command
$basename NAME [SUFFIX]
or
$basename OPTION NAME
‘basename’ command and in case, if you want to strip off the suffix of a file you can give the
filename followed by the SUFFIX name you want to get rid off.
Example:
= basename removes directory path and returns the file
name, kt
$basename /usr/local/bin/kt
Kt
In the first case, the ‘basename’ command removes the directories name from the full path
name given of file ‘kt’ and in the second case ‘basename’ removes the ‘suffix.html’ from
‘kt.html’.
Options for basename command:
‘-a, – -multiple’ option : This option lets you support multiple arguments and treat each as a
NAME
-a is used for multiple inputs
$basename -a /usr/local/bin/kt /usr/local/bin/kt.html
kt kt.html
‘-s, – -suffix = SUFFIX’ option: This option removes a trailing suffix SUFFIX, such as a file
extension.

.html suffix is removed from kt.html


when followed by -s option
Syntax = $basename -s .html kt.html kt
‘-z’ option: This separates the output with NULL rather than a newline.
The outputs of the two arguments passed are not
separated by a newline
Syntax = $basename -az /usr/local/bin/kt kt.html
ktkt.html
2. Base32
To encode or decode data using Base32 in a Unix-like environment (such as Linux or macOS),
you can use the base32 command-line utility.
Base32 Encoding
To encode data to Base32, you can use the following command:
Syntax
echo "Hello, World!" | base32
This will output the Base32 encoded string.
Output
JBSWY3DPEBLW64TMMQ
Base32 Decoding
To decode Base32-encoded data, use the -d flag with the base32 command:
echo "JBSWY3DPEBLW64TMMQ=" | base32 -d
This will output the decoded string.
Output
Hello, World!"
Additional Options
To handle files instead of strings, you can use the base32 command with a file as input:
base32 inputfile.txt
To decode a file from Base32:
base32 -d inputfile. b32
This should help you with Base32 encoding and decoding using the Unix command line.

3. Base64
The base64 command in Unix is used for encoding and decoding data in Base64 format. This
encoding helps in converting binary data into an ASCII string, which is useful for storing or
transmitting data safely.
Example Uses
1. Encoding a String:
echo "Hello, World!" | base64

Output:
SGVsbG8sIFdvcmxkIQo=

2. Decoding a Base64 String:

echo "SGVsbG8sIFdvcmxkIQo=" | base64 --decode


Output:
Hello, World!

3. Encoding a File:

base64 myfile.txt > encoded.txt


This encodes myfile.txt and saves the Base64 output in encoded.txt.

4. Decoding a Base64 File:


base64 --decode encoded.txt > original.txt.
This decodes encoded.txt back to original.txt.

5. Encode binary data (e.g., an image)


base64 image.png > image_base64.txt
This encodes the binary image.png into a text file.

6. Decode binary data back to an image


base64 --decode image_base64.txt > image_decoded.png
4. Bash
Open a new instance of the bash shell.
Syntax
bash [options] [file]
Common Options:
-c "command" → Run a command in Bash
-x → Debug mode (prints executed commands)
-e → Exit immediately if a command fails
-v → Print shell input lines as they are read
--version → Show Bash version Examples:
1. Start an interactive Bash shell bash
This opens a new Bash shell session. Type exit to quit. Running a
command
bash -c "echo 'Hello, World!' "
Output:
Hello, World!
This runs a single command in Bash without starting an interactive session.
5. bc (Basic Calculator) Command
The bc command is a command-line calculator that supports:
Basic arithmetic operations (+, -, *, /)
Floating-point calculations
Variables
Mathematical functions
Basic Usage

1. Perform simple calculations


echo "5 + 3" | bc
Output: 8
2. Use multiplication and division echo
"10 / 3" | bc
Output: 3 (Integer division by default)

3. Enable floating-point precision echo


"scale=2; 10 / 3" | bc
Output: 3.33 (Sets precision to 2 decimal places)

4. Use variables echo


5. "x=5; y=10; x*y" | bc
Output: 50

6. Use bc interactively
Just type bc and press Enter. You can then enter calculations line by line.

7. Use advanced math functions (with -l


option for standard math library) echo
"scale=4; sqrt (25)" | bc -l
Output: 5.0000
6. bg (Background Process) Command
The bg command is used to resume a suspended job in the background. This allows you to keep
running a process while continuing to use the terminal.
The syntax is:
Bg [job_spec]
job_spec can refer to a job number or a specific string related to the command.

Basic Usage

1. Run a long command and suspend it sleep 100


Now press Ctrl+Z to pause (suspend) the process.

2. Send the suspended job to the background bg


The process will continue running in the background.
3. View background jobs jobs
This lists all background jobs.

4. Bring a background job back to the foreground


fg
This moves the last background job back to the foreground.
If multiple jobs exist, use:

fg %1
(where %1 is the job number from jobs)
7. Bind
Set or display readline key and function bindings.
Bind command is a Bash shell builtin command. It is used to set Readline key bindings and
variables. The keybindings are the keyboard actions that are bound to a function. So it can be
used to change how the bash will react to keys or combinations of keys, being pressed on the
keyboard. •
Syntax
bind [-lpsvPSVX] [-m keymap] [-q name] [-f filename] [-u name] [-r keyseq] [-x keyseq:
shell-command] [keyseq: readline-function or readline-command] where,

keyseq: This refers to the key sequence or combination of keys that you want to bind to a
specific function or command. read line-function: These are functions provided by the Readline
library, like moving the cursor, deleting characters, or cutting and pasting text.
shell-command: You can bind key sequences to execute shell commands when pressed.
8. Break command
In Linux, the break command is used in shell scripting (like Bash) to exit a loop prematurely, just
like in programming languages like Python. When the break command is encountered inside a
loop (e.g., for, while, or until), the loop is terminated, and the script continues to execute the
next statement after the loop.
Example of using break in a shell script:
#!/bin/bash
counter=0
while [ $counter -lt 10 ] do
((counter++)) echo
"Counter: $counter"
if [ $counter -eq 5 ]; then
echo "Breaking the loop at counter = $counter" break
fi
done
echo "Loop ended." Explanation:
A while loop runs while $counter is less than 10.
Each time through the loop, it increments $counter and prints the value.
When $counter equals 5, the break command is triggered, terminating the loop. After the loop
ends, the script prints "Loop ended."
Output: vbnet
Counter: 1 Counter: 2
Counter: 3 Counter: 4
Counter: 5
Breaking the loop at counter = 5 Loop
ended.
In this example:
The loop prints the value of counter until it reaches 5, and at that point, it exits the loop due to
the break statement.
After the loop is terminated, the script prints "Loop ended."
9. Builtin
In Linux, a builtin refers to a command that is built directly into the shell rather than being
an external executable.
Syntax
builtin [shell-builtin [arg ..]]
Common Builtin Commands in Bash:
cd – Change directory
echo – Print text to standard output pwd –
Print working directory

exit – Exit the shell


export – Set environment variables alias –
Create command shortcuts
type – Identify whether a command is builtin or external ulimit –
Manage user resource limits set – Configure shell options history
– Display command history
How to Check if a Command is a Builtin:
Use the type command:
Edit type
cd
Output:
cd is a shell builtin or the help
command:
Edit help
cd
10. Bzip2
bzip2 is an external compression tool used to compress files
syntax for the bzip2 command:
bzip2 [options] filename
Common bzip2 Options
Option Description
-k Keep the original file while compressing
-d Decompress the file (same as bunzip2)
-f Force compression even if the file exists
-z Compress the file (default behavior)
-v Verbose mode – show compression progress
-t Test integrity of a .bz2 file
-c Output compressed data to stdout (useful for piping) -# Set
compression level (1 = fastest, 9 = best compression)
e.g. to compress a filebzip2 file.txt

🔹 Creates file.txt.bz2 and deletes file.txt and to


decompress bzip2 -d file.txt.bz2

You might also like