0% found this document useful (0 votes)
26 views5 pages

Sheets

Uploaded by

prathvik.gs01
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)
26 views5 pages

Sheets

Uploaded by

prathvik.gs01
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/ 5

General

#echo "Hello">>x.sh Input and output


#translates all lower to upper read : read input to shell script interactively
echo “enter your name”; read name; echo “Hello $name”
echo "$text"|tr '[:lower:]' '[:upper:]'
paste: join 2 files laterally #Paste file1.txt file2.txt
echo Length of $text is ${#text} System date and time
result=$(echo "sqrt(5+7)" | bc -l) date +"%Y/%m/%d" :displayes date . date +%Y #display year
#settilng precision Date +”%H:%M:%S” #displays time
echo "scale=4; 10/3" | bc -l date -d "+3 days" +"%Y/%m/%d" # future date
echo $result date -d "+3 hours" +"%H:%M:%S" #future time
start_date="2023-01-01"
chmod
end_date=$(date +"%Y-%m-%d")
r (read) = 4 ,chmod a+rwx file.txt
diff=$((($(date -d "$end_date" +%s) - $( date -d "$start_date"
w (write) = 2 ,chmod 754 file.txt +%s))/86400))
x (execute) = 1 Echo “Days bw $start_date and $end_date is: $diff”
chown Vim commands
chown [options] user[:group] file/directory vi +3 f1 : open the file f1 and position the cursor at line 3
chown newuser:newgroup file.txt vi +/pat f1 :open and position at the 1st occurrence of pat
chown --reference=reference_file target_file vi + foo :open and position the cursor at the end
chown -R bob /home/project vi -R foo : open foo in read only mode, prevent changes
egrep vi -o f1 f2 :open multipls files in vertical mode
egrep [options] "pattern" file vi -O f1 f2 :opens fies in horizontal split mode
egrep "apple|orange" fruits.txt #apple or orange :w #save and remain in editing mode
egrep -i "apple" fruits.txt #case insensitive :w bar #save the file as bar (similar to save as)
egrep -i -c "apple" fruits.txt #count the lines :w ! bar #overwrite existing bar without confirmation
egrep -n -i "apple" fruits.txt #display line no. :x #save the file and quit editing mode
egrep "cat.*" animals.txt :q #quit editing mode when no changes are made
egrep "[0-9]+" numbers.txt :q! #quit editing mode and abandon changes
egrep -w "apple" fruits.txt #whole word match yy - Copies the current line.
egrep -v -i "iii" fruits.txt #invert match 6yy - Copies six lines.
egrep -l "pattern" f1 f2 … #gives files name y - Copies a selected region.
egrep -r "apple" linuxprac/ #for a directory p - Pastes copied text after the cursor.
egrep -C 1 "apple" fruits.txt #show bfr and after P - Pastes copied text before the cursor.
egrep "^[1-9]+" fruits.txt #only numbers x - Deletes the character under the cursor.
Arithmetic 6x - Deletes the current character and five to the right.
expr 3 + 5 #note the gap.echo "5+3" |bc #outputs 8 dd - Deletes the current line.
((x=5+3)), x=$((5+3)) and echo $x.let “x=5+6” ,echo $x outputs 8 4dd - Deletes four lines.
Text processing commands dw - Deletes a word under the cursor.
head file.txt #beginning of a file i - Inserts text to the left of the cursor.
tr #translate or delete characters a - Appends text to the right.
tr [options] SET1 [SET2], tr 'a-z' 'A-Z' < input.txt > output.txt o - Opens a new line below.
tr -d 'aeiouAEIOU' < input.txt > output.txt #removes vowels O - Opens a new line above.
tr ' ' ',' < input.txt > output.txt #replaces space with commas u - Undoes the last command.
sort filename.txt #Sort lines in a file in ascending order [Ctrl-r] - Redoes the last undone change.
sort -r filename.txt #descending order U - Undoes all changes to the current line.
sort -n numbers.txt #sort numerically :!cmd - Executes a UNIX command.
sort -f file.txt #lines sorted ignoring case or [Ctrl-z] - Escapes to the UNIX shell temporarily.
uniq filename.txt #Remove consecutive duplicate lines SED commands
uniq -c filename.txt #consecutive # of occurrences of each line sed [options] 'pattern(s) command' input_file(s)
uniq -d filename.txt #Show only the lines that are repeated Replace the first occurrence of "fruits" with "apples"
uniq -i filename.txt #Treat lines as identical regardless of case: -sed 's/fruits/apples/' fruit.txt
Uniq -f #lines that occur only once Replace all occurrences of "apples" with "oranges" and edit the file
sort filename.txt | uniq #remove all duplicates in-place # sed -i 's/apples/oranges/g' fruit.txt
File display a manipulation Search for "fruits" and replace with "oranges" ignoring case, and
cat file.txt #display file content redirect output to # sed 's/fruits/oranges/gi' fruit.txt > orange.txt
cat file1.txt file2.txt>new.txt #combine multiple files Replace all occurrences of "fruits" with "apples" globally across the
Cat f1.txt>>f2.txt #concatenate f1 to f2 file: sed 's/fruits/apples/g' fruit.txt
cat fruits.txt | head -n 2 #display first 2 lines Replace "fruits" with "apples" globally, case-insensitive:
ls -l | egrep "^d" #lists all the directories in present dir sed 's/fruits/apples/gi' fruit.txt
tail -f #monitor and display the last part of a file in real-time sed 's|fruits|apples|gi' fruit.txt
tail -f file.txt # display last lines(10 default)
tail -n 10 -f file.txt #displays last lines
● |: Alternate delimiter. This is helpful when the pattern
System and user info
hostname #name of the local host. Uname #OS name or replacement text contains / to avoid escaping it.
Uname -r #OS release .Who #Users and activities ● g: Global flag ensures all occurrences of "fruits" are
Passwd #change own password replaced.
Su # superuser from nonprivilaged account ● i: Case-insensitive flag ensures that "Fruits",
exit ,logout #terminate shell script "FRUITS", etc., are also replaced.
ssh and remote access
ssh -p port_no user@remote_host
sed '1,2s/fruits/apples/gi' fruit.txt
scp local_file user@remote:/path # copy local to remote machine
scp user@remote:/remote_path local_path/ #remote to local copy
Env and variables ● 1,2: Specifies the line range (from line 1 to line 2) for
set :assign values to positional parameters the substitution.
export : pass variable value to sub-shell
● s/fruits/apples/gi: Replaces all occurrences of sed '/[aeiou]/d' file # Deletes lines containing vowels.
"fruits" with "apples" on the specified lines, ignoring sed '/[0-9]/d' file # Deletes lines containing numbers.
case. sed '2,4d' file # Deletes lines 2 to 4.

# At the line before “i”


sed '2,$s/fruits/apples/gi' fruit.txt
sed '/banana/i This is a fruit:' file # Inserts "This is a fruit:"
before lines containing "banana".
● This replaces "fruits" with "apples" from line 2 to the sed '/^apple/i This starts with "apple".' file # Inserts "This starts with
end of the file. 'apple'." before lines starting with "apple".

sed "s/fruits/$(echo apples | tr a-z A-Z)/gi" # At the line after “a”


sed '/banana/a This is a fruit:' file # Inserts "This is a fruit:"
fruit.txt
after lines containing "banana".
sed '/^apple/a This starts with "apple".' file # Inserts "This starts
● $(echo apples | tr a-z A-Z): This command with 'apple'." after lines starting with "apple".
transforms the replacement string "apples" into
uppercase ("APPLES"). The tr command translates all # At the beginning of the line “s/^/”
lowercase letters (a-z) to uppercase (A-Z). sed '/banana/s/^/The fruit is:/' file # Adds "The fruit is:" at the
● Double quotes: When using shell substitution within a beginning of lines containing "banana".
sed command, you must use double quotes instead
of single quotes so the shell can interpret the # At the end of the line “s/$/”
command. sed '/banana/s/$/ is a fruit/' file # Adds " is a fruit" at the end
of lines containing "banana".
AWK
sed -E 's/(apple|banana)/fruit/g' file awk '{ print $1 }' names.txt # No pattern, only action. Prints the
first column of a file.
● -E: Enables Extended Regular Expressions (ERE), awk -F',' '{ print $2 }' contacts.csv # Field separator -F','
which simplifies the use of parentheses, alternation, (default is space). Prints the second column.
and other features. awk -F',' '{ print $2 , $4 }' contacts.csv # Prints the second and
● (apple|banana): Matches either "apple" or fourth columns.
awk -F',' '{ print $2 + $4 }' contacts.csv # Performs mathematical
"banana".
operation (sum of second and fourth columns).
● fruit: Replacement string.
awk '$2 > 80 { print }' scores.txt # Prints lines where the second
● g: Global flag to replace all occurrences on each line. field is greater than 80.
awk '/error/ { print }' log.txt # Prints lines containing the pattern
sed -E 's/(apple) pie/\1 strudel/g' file "error".
awk 'NR >= 10 { print }' book.txt # Prints lines starting from line
10 onwards.
● (apple): Captures the word "apple".
awk 'NR <= 10 { print }' book.txt # Prints the first 10 lines.
● \1: Refers to the first capture group (i.e., "apple"). awk 'NR >= 10 && NR <= 20 { print }' book.txt # Prints lines
● The command replaces "apple pie" with "apple strudel", from 10 to 20.
keeping "apple" intact. awk 'NF > 3 { print }' scores.txt # Prints lines with more than 3
fields
sed -E 's/(apple|orange) juice/\1 smoothie/g' # Calculating the sum of numbers
file awk '{ sum += $1 } END { print "Sum:", sum }' numbers.txt #
Calculates the sum of the first column.
# Calculating the average of numbers
● (apple|orange): Matches either "apple" or "orange" awk '{ sum += $1 } END { average = sum / NR; print "Average:",
and captures it. average }' grades.txt # Calculates the average of the first column
● \1: Refers to the matched word (either "apple" or # Performing arithmetic operations
"orange"). awk '{ result = $1 + $2 + $3; print $1, $2, $3, "=", result }'
● The command replaces "apple juice" or "orange juice" operations.txt # Adds the first 3 columns and prints the result.
with "apple smoothie" or "orange smoothie", BASH SCRIPTING
respectively. echo "Hello, $(whoami)!."
date
sed -E 's/[0-9]+/NUM/g' file ls -l

echo "what is your name"; read name ;echo hello $name;


● [0-9]+: Matches one or more digits (the + allows for mkdir $name ; cd $name; touch tt.sh; echo "hello $name">> tt.sh
matching multiple digits). #program to calculate sum and product of first N numbers
● NUM: The replacement string for any sequence of digits. echo "Enter a number"; read N ; sum=0; product=1
for (( i=1; i<=N; i++ ))
sed -n '/banana/p' file # print line containing "banana" do
sed -n '/banana/!p' file # print lines NOT containing "banana" sum=$((sum + i))
sed -n '/^apple/p' file # print line starting with "apple" product=$((product * i))
sed -n '/^$/p' file # print empty lines done
sed -n '/^$/!p' file # print non-empty lines echo "sum of the first $N : $sum" ;echo "product is: $product"
sed -n '2,4p' file # print lines 2 to 4 #Reverse a string by taking input
sed -n '/[aeiou]/p' file # print line containing any vowel echo enter a string; read input_string; reversed_string=""
sed -n '/[0-9]/p' file # print line containing numbers for (( i=${#input_string}-1; i>=0; i-- ))
sed -n 's/apple/date/gp' file # replace "apple" with "date" and print do
the modified lines reversed_string+="${input_string:i:1}"
sed '/banana/d' file # Deletes lines containing "banana". done
sed '/^apple/d' file # Deletes lines starting with "apple". echo "The reversed string is: $reversed_string"
sed '/^$/d' file # Deletes empty lines. #Count Vowels
echo "enter a string";read input_string; vowel_count=0 i. file vs folder (-f, -d) ii. Does it exist? (-e) iii. Is it readable,
vowels="aeiouAEIOU" writable, executable, empty (-r, -w, -x. -s) iv. If I am owner or group
for (( i=0; i<${#input_string}; i++ )) (-O, -G) v. date comparison (-nt, -ot)
do # Check if string is non-empty and contains "unix"
char="${input_string:i:1}" # Get the current character read -p "Enter a string: " str
if [[ $vowels == *"$char"* ]]; then if [ -n "$str" ] && [[ "$str" == *unix* ]]; then
((vowel_count++)) # Increment the counter if it's a vowel echo "Valid string"
fi else
done echo "Invalid string"
echo "The number of vowels in the string is: $vowel_count" fi
# Check if file exists # Check if number is greater than 50 and less than 200
if [ -f "file.txt" ]; then read -p "Enter a number: " num
echo "File exists" if [ $num -gt 50 ] && [ $num -lt 200 ]; then
else echo "Number is in the valid range"
echo "File does not exist" else
fi echo "Number is out of range"
# Check if two strings are equal fi
str1="hello" # Check if sum of two numbers is greater than 100
str2="hello" read -p "Enter first number: " num1
if [ "$str1" = "$str2" ]; then read -p "Enter second number: " num2
echo "Strings are equal" if (( num1 + num2 > 100 )); then
fi echo "Sum is greater than 100"
# Check if it's a directory else
dir="mydir" echo "Sum is 100 or less"
if [ -d "$dir" ]; then Fi
echo "It's a directory" #while loop, sum of digits
fi read -p "Enter a positive integer: " number
CASES sum=
read -p "Enter a day: " day if ! [[ "$number" =~ ^[0-9]+$ ]]; then
day=$(echo "$day" | tr '[:upper:]' '[:lower:]') echo "Please enter a valid positive integer."
case $day in exit 1
monday|tuesday|wednesday|thursday|friday) fi
echo "Weekday" while [ "$number" -gt 0 ]; do
;; digit=$(( number % 10 )) # Get the last digit
saturday|sunday) sum=$(( sum + digit )) # Add the digit to the sum
echo "Weekend" number=$(( number / 10 )) # Remove the last digit
;; done
*) echo "The sum of the digits is: $sum"
echo "Invalid day" #sum of elements at even position in array
;; # Read integers from a file into an arry
esac arr=()
# Check if string starts with "abc" while read -r line; do
read -p "Enter a string: " str arr+=("$line")
if [[ "$str" == abc* ]]; then done < "numbers.txt" # Replace with your filename
echo "String starts with abc"
fi sum=0
# Check if string contains "bash" for (( i=0; i<${#arr[@]}; i+=2 )); do
read -p "Enter a string: " str sum=$(( sum + arr[i] ))
if [[ "$str" == *bash* ]]; then done
echo "String contains bash" echo "Sum of even-indexed elements: $sum"
Fi #create associate arrat of countries and capital
# Check string length # Declare associative array
read -p "Enter a string: " str declare -A capitals
if [ ${#str} -gt 10 ]; then capitals=( [USA]="Washington, D.C." [France]="Paris"
echo "String is long" [Germany]="Berlin" )
else for country in "${!capitals[@]}"; do
echo "String is short" echo "The capital of $country is ${capitals[$country]}"
fi done
# Check if string is "yes" or "y" #write array in reverse
read -p "Enter a string (yes/y): " response arr=(1 2 3 4 5)
if [ "$response" = "yes" ] || [ "$response" = "y" ]; then for (( i=${#arr[@]}-1; i>=0; i-- )); do
echo "Affirmative" echo "${arr[i]}"
else done
echo "Negative" # Recursive function to calculate factorial
fi factorial() {
# Check if string is "admin" and user ID is greater than 1000 if [ "$1" -le 1 ]; then
read -p "Enter username: " user echo 1
read -p "Enter user ID: " uid else
if [ "$user" = "admin" ] && [ $uid -gt 1000 ]; then local prev_fact
echo "Admin user" prev_fact=$(factorial "$(( $1 - 1 ))")
else echo $(( $1 * prev_fact ))
echo "Regular user" fi
Fi }
read -p "Enter a number: " num
result=$(factorial "$num")
echo "Factorial of $num is $result" echo "Line $line_number has $word_count words."
#guessing game ((line_number++))
# Generate a random number between 1 and 100 done < "$filename"
target=$(( RANDOM % 100 + 1 )) #linux commands
guess=0 ls *.out 2>/dev/null | wc -l # Counts the number of .out files in the current
attempts=0 directory.
grep "ENERGY" *.out # Searches for the keyword "ENERGY" in all .out files.
echo "Welcome to the Number Guessing Game!"
ls d*.hsd # Lists files starting with "d" and ending with ".hsd".
echo "I have selected a number between 1 and 100. Can you find . -name "*.out" -exec wc -l {} + | awk '{s+=$1} END {print s}' # Recursively
guess it?" counts the total number of lines in .out files.
while [ "$guess" -ne "$target" ]; do find . -type f -mtime -7 # Lists files modified in the last 7 days.
read -p "Enter your guess: " guess grep -o "\*\*\*" out | wc -l # Counts occurrences of "***" in a file named out.
((attempts++)) sed -n '10,20p' out # Displays lines 10 to 20 from the file "out".
du -h * # Displays the size of each file in the directory in a human-readable
if [ "$guess" -lt "$target" ]; then
format
echo "Too low! Try again." ls -lS # Lists files sorted by size from largest to smallest.
elif [ "$guess" -gt "$target" ]; then sort names.out | uniq # Displays all unique lines from "names.out".
echo "Too high! Try again." grep "energy" out | awk '{print $3, $5}' # Extracts lines with "energy" and
else displays the 3rd and 5th columns.
echo "Congratulations! You've guessedr: $target" grep "energy" out | awk '{printf "%.5f %.5f\n", $3, $5}' # Extracts the 3rd and
5th columns, rounding them to five decimal places.
echo "It took you $attempts attempts."
ls -d */ # Lists only directories in the current working directory.
fi find . -type f -empty # Lists all empty files in the directory.
done find . -type f -size +10M # Lists all files larger than 10MB.
# Deletes all lines starting with the number '3' in a file.
sed -i '/^3/d' your_file.txt # grep "go*l" file.txt # Matches "gl", "gol", "gool", "gooool", and so on.
# inserts "Your text here" after every 5th line in a file. grep "12*34" file.txt # Matches "1234", "12234", "122234", and so..
awk 'NR % 5 == 0 { print; print "Your text here"; next }1' your_file.txt grep "c.t" file.txt # Matches "cat", "cet", "cft", but not "ct" or "catt".
> temp.txt && mv temp.txt your_file.txt grep "a.b" file.txt # Matches "abb", "acb", "aab", but not "ab" or
# This script replaces the first word of each line with "Hello". "aabb".
sed -i 's/^\w\+/Hello/' your_file.txt # Replace 'your_file.txt' with your grep "a.*b" file.txt # Matches "ab", "aabb", "aXb", etc.
actual filename grep "[aeiou]" file.txt # Matches any lowercase vowel.
# reverses the order of words in each line. grep "[1-3]" file.txt # Matches a digit between 1 and 3.
sed -E 's/(.*) (.*)/\2 \1/' your_file.txt # Adjust the regex for multiple grep "[^Z]" file.txt # Matches any character except "Z".
words if needed grep "[^0-9]" file.txt # Matches any non-digit character.
# capitalizes the first letter of each word and appends " - end" grep "^Start" file.txt # Matches "Start" at the beginning of a line.
to each line. grep "sun$" file.txt # Matches "sun" at the end of a line.
sed -E 's/\b([a-z])/\U\1/g; s/$/ - end/' your_file.txt # Replace grep "g\+" file.txt # Matches one or more occurrences of "g".
'your_file.txt' with your actual filename grep "colou\?r" file.txt # Matches "color" and "colour".
# Thiscalculates and prints the average of numbers in grep "GIF\|JPEG" file.txt # Matches "GIF" or "JPEG".
'numbers.txt'. grep "wood\(cock\|house\)" file.txt # Matches "woodcock" or
awk '{ total += $1; count++ } END { print "Average:", total/count }' "woodhouse".
numbers.txt grep "\{3\}" file.txt # Matches exactly 3 occurrences of the previous
# This script finds and prints the maximum and minimum character.
values from 'values.txt'. grep "\d\{3\}" file.txt # Matches any three-digit number.
awk 'NR == 1 { min = max = $1 } { if ($1 < min) min = $1; if ($1 > grep "\w\+" file.txt # Matches one or more word characters.
max) max = $1 } END { print "Min:", min, "Max:", max }' values.txt grep "\s\+" file.txt # Matches one or more whitespace characters.
# This script calculates and prints letter grades based on grep "[[:alpha:]]\+" file.txt # Matches one or more alphabetic
scores in 'grades.csv'. characters.
awk -F, '{ grep "[[:upper:]][[:digit:]]" file.txt # Matches an uppercase letter
if ($2 >= 90) grade = "EX"; followed by a digit.
else if ($2 >= 80) grade = "A"; grep "[[:space:]]" file.txt # Matches any whitespace character.
else if ($2 >= 70) grade = "B"; grep "[[:punct:]]" file.txt # Matches punctuation characters like ".",
else if ($2 >= 60) grade = "C"; "!", "?", etc.
else grade = "F";
print $1, grade alias # Abbreviate a command sequence.
}' grades.csv cd dirname # Change current directory to dirname.
# This script calculates and prints the total sales revenue for chmod # Change file's permissions.
each product and overall total from 'sales.csv'. chown # Change file's ownership.
awk -F, '{ revenue = $2 * $3; total += revenue; print $1, revenue } cp # Copy file.
END { print "Total Sales Revenue:", total }' sales.csv grep # Lines containing a pattern.
# This script computes and prints the percentage increase in gzip # Compress file (to .gz).
sales from one month to the next in 'salesdata.csv'. ls -l # List directory contents in long format.
awk 'NR == 1 { prev = $1; next } { increase = (($1 - prev) / prev) * mv # Move files to another directory.
100; print "Percentage increase:", increase "%"; prev = $1 }' pwd # Print working directory.
salesdata.csv rm # Remove files or directories.
# counts the no of words in each line of a file sed # Stream editor for filtering and transforming text.
read -p "Enter the filename: " filename ssh # Log in to a remote machine.
if [[ ! -f "$filename" ]]; then tar # Archive and extract files.
echo "File does not exist." touch # Change file's timestamp or create empty file.
exit 1 uname -r # Display operating system release.
fi wc # Count lines, words, and characters in a file.
line_number=1 df -h # Display disk space usage in human-readable format.
while IFS= read -r line; do du # Show disk space usage of files and directories.
word_count=0 head # Output the first part of files.
for word in $line; do tail -f # Output the last part of a file and track it live.
((word_count++)) top # Display real-time system resource usage.
done ps aux # List all running processes.

You might also like