diff --git a/tutorials/learnshell.org/en/Input Parameter Parsing.md b/tutorials/learnshell.org/en/Input Parameter Parsing.md new file mode 100644 index 000000000..7abfe7499 --- /dev/null +++ b/tutorials/learnshell.org/en/Input Parameter Parsing.md @@ -0,0 +1,146 @@ +**Input Parsing Parameters in Bash** + +--- + +Bash scripts are incredibly useful for automating tasks in Linux environments. Often, you'll need to create scripts that accept input parameters. In this tutorial, we'll cover how to parse input parameters in a Bash script using `getopts`. + +--- + +### **Tutorial** + +Bash provides the `getopts` built-in for parsing options and arguments. Options typically begin with a hyphen (`-`) and can be combined together. For example, `-a -b -c` can be combined as `-abc`. We’ll also show how to handle optional arguments using `getopts`. + +In this tutorial, you'll learn: +- How to parse short options like `-a`, `-b` using `getopts`. +- How to handle required and optional arguments. +- How to handle invalid options. + +#### **How `getopts` Works** + +The basic syntax for `getopts` is: +```bash +while getopts "abc:" opt; do + case $opt in + a) + echo "Option a was triggered" + ;; + b) + echo "Option b was triggered" + ;; + c) + echo "Option c was triggered with argument: $OPTARG" + ;; + \?) + echo "Invalid option: -$OPTARG" >&2 + ;; + esac +done +``` + +- The string `"abc:"` indicates that options `-a`, `-b` do not require an argument, while `-c` requires an argument (indicated by the colon). +- `$OPTARG` stores the argument provided for options that require one. + +--- + +### **Exercise** + +Create a Bash script that accepts three options: `-n`, `-u`, and `-f`, where: +- `-n` requires a name (string argument). +- `-u` is a flag that converts the name to uppercase. +- `-f` is a flag that converts the name to lowercase. + +**Objective**: Write a script that parses the options and prints the modified name according to the flags. + +--- + +### **Tutorial Code** + +Here is a starting point for your script: +```bash +#!/bin/bash + +while getopts "n:uf" opt; do + case $opt in + n) + name=$OPTARG + ;; + u) + to_upper=true + ;; + f) + to_lower=true + ;; + \?) + echo "Invalid option: -$OPTARG" >&2 + exit 1 + ;; + esac +done + +# Your logic here for converting the name +``` + +--- + +### **Expected Output** + +If the script is run as: +```bash +./myscript.sh -n "John Doe" -u +``` + +The output should be: +``` +JOHN DOE +``` + +If the script is run as: +```bash +./myscript.sh -n "John Doe" -f +``` + +The output should be: +``` +john doe +``` + +--- + +### **Solution** + +Here is a complete solution for the exercise: +```bash +#!/bin/bash + +while getopts "n:uf" opt; do + case $opt in + n) + name=$OPTARG + ;; + u) + to_upper=true + ;; + f) + to_lower=true + ;; + \?) + echo "Invalid option: -$OPTARG" >&2 + exit 1 + ;; + esac +done + +# Apply transformations based on flags +if [ "$to_upper" = true ]; then + name=$(echo "$name" | tr '[:lower:]' '[:upper:]') +elif [ "$to_lower" = true ]; then + name=$(echo "$name" | tr '[:upper:]' '[:lower:]') +fi + +echo "$name" +``` + +--- + +This tutorial shows how to parse input parameters in Bash and apply transformations based on the provided options. By following the structure, you can extend this logic to more complex scenarios in your Bash scripts. + diff --git a/tutorials/learnshell.org/en/Regular Expressions.md b/tutorials/learnshell.org/en/Regular Expressions.md new file mode 100644 index 000000000..f6477e12a --- /dev/null +++ b/tutorials/learnshell.org/en/Regular Expressions.md @@ -0,0 +1,122 @@ + +--- + +**Using Regular Expressions (Regex) in Bash** + +--- + +Regular expressions (regex) are powerful tools for matching patterns within strings. In Bash, regex is often used in combination with tools like `grep`, `sed`, and within conditional statements using `[[ ]]`. In this tutorial, we'll explore how to use regex in Bash scripts effectively. + +--- + +### **Tutorial** + +A regular expression defines a search pattern that can be used to match strings. In Bash, regex is primarily used for: +- Validating input (e.g., ensuring an email format). +- Extracting parts of a string based on patterns. +- Searching and replacing text. + +This tutorial covers: +- Basic regex syntax in Bash. +- How to use regex within `[[ ]]` and `grep`. +- Handling regex in scripts for different tasks like pattern matching and input validation. + +#### **Regex Syntax Overview** + +Here are some common regex patterns: +- `^`: Matches the beginning of a string. +- `$`: Matches the end of a string. +- `.`: Matches any single character. +- `[abc]`: Matches any character `a`, `b`, or `c`. +- `*`: Matches zero or more occurrences of the preceding character. +- `+`: Matches one or more occurrences of the preceding character. + +For example, the pattern `^[a-zA-Z]+$` matches a string containing only alphabetic characters. + +#### **Using Regex in Bash** + +In Bash, you can use regex within `[[ ]]` for pattern matching: +```bash +if [[ "Hello123" =~ ^[A-Za-z]+$ ]]; then + echo "Only letters found!" +else + echo "Contains non-letter characters." +fi +``` +In the above code: +- The pattern `^[A-Za-z]+$` checks if the string contains only letters. + +--- + +### **Exercise** + +Create a Bash script that: +- Accepts a string as input. +- Validates if the string is a valid email address using regex. +- If the input is a valid email, print "Valid email". Otherwise, print "Invalid email". + +**Hint:** A basic regex for an email can be something like `^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$`. + +--- + +### **Tutorial Code** + +Start with the following code: +```bash +#!/bin/bash + +read -p "Enter your email: " email + +if # add you statement here; then + # add a if else condition and print out the changes +fi +``` + +--- + +### **Expected Output** + +When the script is run: +```bash +./validate_email.sh +``` + +For the input: +``` +Enter your email: user@example.com +``` +The expected output is: +``` +Valid email +``` + +For an invalid email input: +``` +Enter your email: user@invalid +``` +The output should be: +``` +Invalid email +``` + +--- + +### **Solution** + +Here’s the complete solution: +```bash +#!/bin/bash + +read -p "Enter your email: " email + +# Regex to validate an email address +if [[ $email =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then + echo "Valid email" +else + echo "Invalid email" +fi +``` + +--- + +This tutorial gives you a solid foundation in using regex in Bash for pattern matching and validation. Regex is a powerful tool that, when combined with Bash scripting, can automate many text-processing tasks. diff --git a/tutorials/learnshell.org/en/Special Commands (sed, awk, grep, sort).md b/tutorials/learnshell.org/en/Special Commands (sed, awk, grep, sort).md new file mode 100644 index 000000000..2cf9f544c --- /dev/null +++ b/tutorials/learnshell.org/en/Special Commands (sed, awk, grep, sort).md @@ -0,0 +1,161 @@ +**Mastering Special Commands: `sed`, `awk`, `grep`, and `sort` in Bash** + +--- + +In Bash, commands like `sed`, `awk`, `grep`, and `sort` are indispensable for text processing and data manipulation. These tools allow you to perform everything from simple text searches to complex data transformations with minimal effort. This tutorial delves into each command’s unique capabilities, showing how you can leverage them in your Bash scripts. + +--- + +### **Tutorial** + +#### **1. `grep`: Pattern Searching** + +`grep` (Global Regular Expression Print) is used to search for patterns within files or output. It’s perfect for finding lines that match a specific pattern. + +**Common Use Cases:** +- Searching for specific keywords in a file. +- Filtering output based on matching patterns. + +**Example:** +```bash +grep "error" logfile.txt +``` +This command searches for the word “error” in `logfile.txt` and returns all matching lines. + +**Options to Note:** +- `-i`: Case-insensitive search. +- `-r`: Recursively search directories. +- `-v`: Invert match (return lines that don’t match the pattern). + +--- + +#### **2. `sed`: Stream Editing** + +`sed` (Stream Editor) is used for parsing and transforming text in files or streams. It’s powerful for find-and-replace operations, text insertion, and deletion. + +**Common Use Cases:** +- Replacing or deleting text in files. +- Extracting specific data from text streams. + +**Example:** +```bash +sed 's/old-text/new-text/g' file.txt +``` +This replaces all instances of `old-text` with `new-text` in `file.txt`. + +**Options to Note:** +- `-i`: Edit the file in place. +- `-n`: Suppress automatic printing; useful with pattern matching. +- `d`: Delete lines that match a pattern. + +--- + +#### **3. `awk`: Text Processing and Reporting** + +`awk` is a versatile command designed for pattern scanning and processing. It allows you to extract and format data from structured text like CSVs, logs, and reports. + +**Common Use Cases:** +- Extracting specific columns from a file. +- Performing calculations on numeric data within text. + +**Example:** +```bash +awk '{print $1, $3}' file.txt +``` +This command prints the first and third columns of each line in `file.txt`. + +**Options to Note:** +- `-F`: Specify a field separator (default is whitespace). +- `NR`: Built-in variable that holds the line number. +- `sum += $2`: Example of performing a calculation (summing the values of the second column). + +--- + +#### **4. `sort`: Sorting Lines of Text** + +`sort` is used to arrange lines of text in alphabetical or numerical order. It’s handy for organizing lists or data before further processing. + +**Common Use Cases:** +- Sorting a list of names alphabetically. +- Sorting numbers in ascending or descending order. + +**Example:** +```bash +sort -n numbers.txt +``` +This sorts the numbers in `numbers.txt` in ascending order. + +**Options to Note:** +- `-r`: Reverse the sort order. +- `-u`: Remove duplicates after sorting. +- `-k`: Sort based on a specific key (e.g., a particular column). + +--- + +### **Exercise** + +Create a Bash script that: +1. Reads a text file containing lines of data in the format: `Name, Age, City`. +2. Filters out lines that contain a specific city using `grep`. +3. Sorts the filtered results by age using `sort`. +4. Extracts only the names and ages using `awk`. +5. Replaces all commas with hyphens using `sed`. + +--- + +### **Tutorial Code** + +Here’s the starting code for the exercise: +```bash +#!/bin/bash + +input_file="people.txt" +city_to_filter="New York" + +# Step 1: Filter lines by city using grep +filtered=$(grep "$city_to_filter" "$input_file") + +# Step 2: Sort by age (2nd column) using sort +sorted=$(echo "$filtered" | sort -t, -k2n) + +# Step 3: Extract names and ages using awk +output=$(echo "$sorted" | awk -F, '{print $1, $2}') + +# Step 4: Replace commas with hyphens using sed +final_output=$(echo "$output" | sed 's/,/-/g') + +echo "$final_output" +``` + +--- + +### **Expected Output** + +For the following input file (`people.txt`): +``` +John Doe,25,New York +Jane Smith,30,Los Angeles +Alice Brown,22,New York +Bob Johnson,28,New York +``` + +Running the script should produce: +``` +Alice Brown 22 +John Doe 25 +Bob Johnson 28 +``` + +--- + +### **Solution** + +The code provided in the exercise is the complete solution, but let’s break down the steps for clarity: +1. `grep "$city_to_filter"` filters out lines containing "New York". +2. `sort -t, -k2n` sorts the filtered lines by the second column (age) numerically. +3. `awk -F, '{print $1, $2}'` extracts only the names and ages. +4. `sed 's/,/-/g'` replaces commas with hyphens, as per the exercise requirements. + +--- + +This tutorial gives you a well-rounded understanding of using `sed`, `awk`, `grep`, and `sort` in Bash scripting. Each of these tools excels at specific tasks, and together they provide a powerful text-processing toolkit.