0% found this document useful (0 votes)
16 views

Linux Practical

The document contains a list of Unix shell scripting experiments, including tasks such as working with the vi editor, calculating factorials using awk, creating menu-driven scripts, and checking if numbers are prime. Each task is accompanied by example scripts and explanations on how they function. Additionally, it covers basic Unix commands, file and directory management, and text processing techniques.

Uploaded by

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

Linux Practical

The document contains a list of Unix shell scripting experiments, including tasks such as working with the vi editor, calculating factorials using awk, creating menu-driven scripts, and checking if numbers are prime. Each task is accompanied by example scripts and explanations on how they function. Additionally, it covers basic Unix commands, file and directory management, and text processing techniques.

Uploaded by

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

List of Experiment

Sr.
No
1. Working with vi editor?

2. Find the factorial of any number using awk


command in unix?
3. Write menu driven shell script to
execute 5 basic command of unix?
4. Write a script to check the no is prime or not?
5. Display the out put of ls l command in user
friendly way?
6. Find greatest among three no using shell
script?
7. Practice of unix basic commands, directory
and files relatedcommands, administrative
commands, advanced commands ,
tr, sed, awk. filters, redirection operators, pipe
operator.
8. Write awk command to count the number
of time each wordoccursin a sorted list that
contains one word per line.
9. Write shell script to check whether the
string is vowel, unix orUNIX it is two
character long?

1
Q1. working with vi editor?

Ans :
1. Opening a File:
• To open a file with Vi, open your terminal and type `vi` followed by the filename. For
example: `vi filename.txt`.
• If the file doesn't exist, Vi will create a new file with that name when you save.

2. Modes:
• Vi has different modes:
• Normal mode: This is the default mode for navigation and issuing commands.
• Insert mode: In this mode, you can insert or edit text.
• Command line mode: This mode allows you to save, quit, and perform otherfilerelated
actions.

3. Basic Navigation (Normal mode):


• `h`, `j`, `k`, `l`: Navigate left, down, up, and right, respectively.
• `w`: Move forward by one word.
• `b`: Move backward by one word.
• `$`: Move to the end of the current line.
• `0` (zero): Move to the beginning of the current line.
• `G`: Move to the end of the file.
• `1G` or `gg`: Move to the beginning of the file.
• `<line number>G`: Move to a specific line (replace `<line number>` with the desiredline
number).

4. Entering Insert Mode:


• `i`: Insert text before the cursor.
• `I`: Insert text at the beginning of the current line.
• `A`: Append text at the end of the current line.
• `o`: Open a new line below the current line.
• `O`: Open a new line above the current line.

5. Exiting Insert Mode:


• To exit insert mode and return to normal mode, press `Esc` key.

6. Saving and Quitting (Commandline mode):


• `:w`: Save changes to the file.

• `:q`: Quit Vi.


• `:q!`: Quit Vi without saving changes.
• `:wq` or `:x`: Save changes and quit.

7. Search and Replace (Normal mode):


• `/`: Search for text. Type the text you want to find and press `Enter`.
• `n`: Move to the next occurrence of the search term.
• `N`: Move to the previous occurrence.
• `:s/old/new/g`: Replace "old" with "new" globally in the current line.
• `:%s/old/new/g`: Replace "old" with "new" globally in the entire file.

8. Undo and Redo (Normal mode):


• `u`: Undo the last change.
• `Ctrl + r`: Redo (undo the undo).

9. Copy, Cut, and Paste (Normal mode):


• `yy`: Copy (yank) the current line.
• `dd`: Cut (delete) the current line.
• `p`: Paste the last copied or cut text.
10. Exiting Vi Temporarily (Normal mode):
- `:e filename`: Open another file.
- `:q` followed by `!`: Quit without saving changes.

Remember that Vi is a powerful text editor with many more commands and features. These are
just the basics to help you get started. The more you use it, the more proficientyou will become.
Q2. find the factorial of any number using awk command in unix?

Ans:
echo "Enter a number: "
read num

awk 'function factorial(n) {if


(n <= 1) return 1;
else return n factorial(n 1);
} BEGIN
{
print "The factorial of", '$num', "is", factorial('$num');
}'

./calculate_factorial.awk
Q3. Write menu driven shell script to execute 5 basic command of unix?

Ans :
#!/bin/bash

while true; do
clear
echo "Basic Unix Command Menu"
echo " "
echo "1. List Files (ls)"
echo "2. Print Working Directory (pwd)"
echo "3. Display Date and Time (date)"
echo "4. List Users (who)"
echo "5. Display Calendar (cal)"
echo "6. Exit"

read p "Enter your choice (16): " choice

case $choice in
1)
echo "Listing Files:"ls
;;
2)
echo "Current Directory:"
pwd
;;
3)
echo "Date and Time:"
date
;;
4)

echo "LoggedIn Users:"


who
;;
5)

echo "Calendar:"
cal
;;
6)

echo "Exiting the script."


exit 0
;;
)

echo "Invalid choice. Please enter a valid option (16)."


;;
esac

read p "Press Enter to continue..."


done
Q4. Write a script to check the no is prime or not?

Ans :
Certainly! Here's a simple menudriven shell script in Unix that allows you to executefive basic
Unix commands: `ls`, `pwd`, `date`, `who`, and `cal`. You can customize it further or add more
commands as needed:

```bash
#!/bin/bash

while true; do
clear
echo "Basic Unix Command Menu"
echo " "
echo "1. List Files (ls)"
echo "2. Print Working Directory (pwd)"
echo "3. Display Date and Time (date)"
echo "4. List Users (who)"
echo "5. Display Calendar (cal)"
echo "6. Exit"

read p "Enter your choice (16): " choice

case $choice in1)


echo "Listing Files:"ls ;; 2)

echo "Current Directory:"


pwd
;;

echo "Date and Time:"date


;;

echo "LoggedIn Users:"who;;

echo "Calendar:"cal;;

echo "Exiting the script."exit 0;;

echo "Invalid choice. Please enter a valid option (16).";;

read p "Press Enter to continue..."


done
```
Here's how the script works:

1. It displays a menu with five basic Unix commands and an option to exit.
2. It reads your choice and performs the corresponding action using a `case` statement.
3. After executing a command, it prompts you to press Enter to continue and clears thescreen
for the next iteration.

To use this script, save it to a file (e.g., `basic_unix_commands.sh`), make it executableusing


`chmod +x basic_unix_commands.sh`, and run it with
`./basic_unix_commands.sh`.

9
Q5. display the out put of ls l command in user friendly way?Ans
:
#!/bin/bash

# Run 'ls l' and store the output in a variable


ls_output=$(ls l)

# Check if the output is empty (no files in the directory)if [


z "$ls_output" ]; then
echo "No files in the directory."
else
# Print a header
echo "Permissions Owner Group Size Last Modified Name"

# Loop through each line of 'ls l' output


while read r line; do
# Extract relevant information and format it
permissions=$(echo "$line" | awk '{print $1}')
owner=$(echo "$line" | awk '{print $3}') group=$(echo
"$line" | awk '{print $4}') size=$(echo "$line" | awk
'{print $5}') modified=$(echo "$line" | awk '{print $6,
$7, $8}')name=$(echo "$line" | awk '{print $9}')

# Print the formatted output


echo "$permissions $owner $group $size $modified $name"done
<<< "$ls_output"
fi
Here's how this script works:

It runs the ls l command and captures its output in the ls_output variable.
It checks if the output is empty (indicating no files in the directory) and handles that case.It prints
a header line to label the columns.
It then processes each line of the ls l output using a while loop, extracting and formattingthe
relevant information (permissions, owner, group, size, modification date, and name) for each file
or directory.
Finally, it prints the formatted output.
Save this script to a file (e.g., ls_friendly.sh), make it executable with chmod +x ls_friendly.sh,
and then run it using ./ls_friendly.sh in the directory you want to list. Thisscript will display the
ls l output in a more userfriendly format.
Q6 . Find greatest among three no using shell script?Ans
:
#!/bin/bash

# Input three numbers


read p "Enter the first number: " num1 read p
"Enter the second number: " num2read p
"Enter the third number: " num3

# Compare the numbers to find the greatest


if [ "$num1" gt "$num2" ]&& [ "$num1" gt "$num3" ]; thenecho
"The greatest number is: $num1"
elif [ "$num2" gt "$num1" ]&& [ "$num2" gt "$num3" ]; thenecho
"The greatest number is: $num2"
else
echo "The greatest number is: $num3"
fi

Here's how this script works:

It takes input for three numbers from the user.


It uses conditional statements (if, elif, and else) to compare the numbers and determinethe
greatest among them.
It prints the result, indicating which of the three numbers is the greatest.
Save this script to a file (e.g., find_greatest.sh), make it executable with chmod +x
find_greatest.sh, and then run it using ./find_greatest.sh. The script will prompt you toenter
three numbers, and it will then display the greatest among them.
Q7. Practice of unix basic commands, directory and files related commands, administrative
commands, advanced commands , tr, sed , awk. filters, redirectionoperators, pipe operator.
Ans :
Basic Commands:

ls: List files and directories.

Example: ls l to list files and directories in long format.


pwd: Print the current working directory.

Example: pwd
cd: Change directory.

Example: cd /path/to/directory
mkdir: Create a new directory.

Example: mkdir new_directory


touch: Create an empty file.

Example: touch new_file.txt


File and Directory Related Commands:
6. cp: Copy files and directories.

Example: cp file.txt new_directory/


mv: Move or rename files and directories.

Example: mv file.txt new_name.txt


rm: Remove files and directories.

Example: rm file.txt
find: Search for files and directories.

Example: find /path/to/search name ".txt"


Administrative Commands:
10. sudo: Execute commands with superuser privileges.

- Example: sudo apt update

useradd: Add a new user.

Example: sudo useradd newuser


userdel: Delete a user.

Example: sudo userdel existinguser


Advanced Commands:
13. tar: Create and extract archive files.

- Example: tar cvzf archive.tar.gz directory_to_archive

grep: Search for text patterns in files.


Example: grep "pattern" file.txt
Text Processing (Using tr, sed, and awk):
15. tr: Translate or delete characters.
- Example: echo "Hello" | tr '[:lower:]' '[:upper:]'

sed: Stream editor for text manipulation.


Example: sed 's/old/new/g' input.txt > output.txt awk:
Text processing tool with scripting capabilities.

Example: awk '{print $1}' data.txt


Filters:
18. sort: Sort lines in text files.

- Example: sort file.txt

cut: Remove sections from each line of files.


Example: cut d, f13 data.csv
Redirection Operators and Pipes:
20. >: Redirect output to a file.
- Example: ls > file_list.txt

>>: Append output to a file.

Example: echo "New line" >> file.txt


|: Pipe operator to combine commands.

Example: cat file.txt | grep "pattern"


Practice these commands and concepts on your Unix/Linux system to become more
proficient in working with files, directories, and text processing.
Q8. Write awk command to count the number of time each word occurs in a sortedlist that
contains one word per line.
Ans : awk '
{
if ($0 != prev) { if
(prev != "") {
print prev, count
}
prev = $0
count = 1
} else {
count++
}
}
END {
print prev, count
}
' sorted_list.txt
Here's how this awk command works:

It reads each line from the sorted_list.txt file.


If the current line ($0) is different from the previous line (prev), it prints the previousword and
its count.
If the current line is the same as the previous line, it increments the count.Finally, in the
END block, it prints the last word and its count.
Q9. write shell script to check whether the string is vowel, unix or UNIX it is twocharacter
long?
Ans:
#!/bin/bash

# Function to check if a string is one of the specified values


check_string() {
local input="$1"

# Convert the input to lowercase for caseinsensitive comparison


input="${input,,}"

case "$input" in
"vowel" | "unix" | "unix")
echo "The string \"$input\" is valid."
;;
)
echo "The string \"$input\" is not valid."
;;
esac
}

# Input
read p "Enter a twocharacter string: " user_input

# Check the input


if [ ${#user_input} eq 2 ]; then
check_string "$user_input"
else
echo "Please enter a twocharacter string."
Fi
Here's how the script works:

It defines a function checkstring that checks whether the input string matches "vowel,""unix," or
"UNIX" (caseinsensitive).

The script takes user input and checks if it is a twocharacter string.

If the input is two characters long, it calls the checkstring function to verify whether itmatches
one of the specified values. If it matches, it outputs that the string is valid; otherwise, it's not
valid.

Save this script to a file (e.g., check_string.sh), make it executable with chmod +x
check_string.sh, and then run it with ./check_string.sh. It will prompt you to enter a two
character string and tell you whether it matches the specified values
Q10. Write a script to check the no is prime or not?

Ans :
Certainly! Here's a simple menudriven shell script in Unix that allows you to executefive basic
Unix commands: `ls`, `pwd`, `date`, `who`, and `cal`. You can customize it further or add more
commands as needed:

```bash
#!/bin/bash

while true; do
clear
echo "Basic Unix Command Menu"
echo " "
echo "1. List Files (ls)"
echo "2. Print Working Directory (pwd)"
echo "3. Display Date and Time (date)"
echo "4. List Users (who)"
echo "5. Display Calendar (cal)"
echo "6. Exit"

read p "Enter your choice (16): " choice

case $choice in1)


echo "Listing Files:"ls ;; 2)

echo "Current Directory:"

19
pwd
;;

echo "Date and Time:"date


;;

echo "LoggedIn Users:"who;;

echo "Calendar:"cal;;

echo "Exiting the script."exit 0;;

echo "Invalid choice. Please enter a valid option (16).";;

read p "Press Enter to continue..."


done
```

Here's how the script works:


4. It displays a menu with five basic Unix commands and an option to exit.
5. It reads your choice and performs the corresponding action using a `case` statement.
6. After executing a command, it prompts you to press Enter to continue and clears thescreen
for the next iteration.

To use this script, save it to a file (e.g., `basic_unix_commands.sh`), make it executableusing


`chmod +x basic_unix_commands.sh`, and run it with
`./basic_unix_commands.sh

You might also like