WECM100/b009.sh Script Explanation

This script demonstrates basic string manipulation in a Linux shell environment, specifically within WSL (Windows Subsystem for Linux) on Windows 11. It focuses on trimming whitespace and special characters, and changing the case of strings.

Script Content (b009.sh):

#!/bin/bash

# remove "\n" "-" " "
phone=" 04-1111-2222 "
echo "$phone" | tr -d " -" | tr -d '\n'
trim=$(echo "$phone" | tr -d "-")
echo "$trim" | tr -d '\n'

# lowercase uppercase -------------------
fruit="Apple"
echo "$fruit" | tr A-Z a-z | tr -d '\n'
echo "$fruit" | tr a-z A-Z

# sed stream edit ---------------
echo "$phone" | sed 's/-//g' | tr -d '\n'
echo "$phone"
    

Explanation:

  1. Trimming Characters:
    • phone=" 04-1111-2222 ": Defines a string variable with leading/trailing spaces and hyphens.
    • echo "$phone" | tr -d " -" | tr -d '\n': Uses tr to delete spaces, hyphens, and newline characters.
    • trim=$(echo "$phone" | tr -d "-"): Stores the result of removing hyphens in the trim variable.
    • echo "$trim" | tr -d '\n': Removes newline characters from the trim variable.
  2. Case Conversion:
    • fruit="Apple": Defines a string variable.
    • echo "$fruit" | tr A-Z a-z | tr -d '\n': Converts uppercase to lowercase and removes newline.
    • echo "$fruit" | tr a-z A-Z: Converts lowercase to uppercase.
  3. Using sed:
    • echo "$phone" | sed 's/-//g' | tr -d '\n': Uses sed to replace all hyphens with nothing (effectively deleting them) and then removes newline characters. s/-//g means substitute all (-) with nothing globally (g).
    • echo "$phone": Prints the original phone variable.

How to Run:

  1. Open WSL on Windows 11.
  2. Navigate to the directory where you want to create the script: cd ./WECM100
  3. Create the script using nano b009.sh and paste the script content.
  4. Make the script executable: chmod +x b009.sh
  5. Run the script: ./b009.sh

Expected Output:

0411112222
0411112222
apple
APPLE
0411112222
 04-1111-2222
    

This script is a simple example for embedded beginners to understand basic string manipulation in a Linux shell environment. The tr and sed commands are powerful tools for text processing.