Text Processing and Shell Scripting

Level: Beginner Module: Linux Fundamentals 7 min read Lesson 7 of 10

Overview

  • What you’ll learn: How to process text with grep, sed, and awk, use pipes and redirection, and write bash shell scripts.
  • Prerequisites: Lesson 6 – Package Management with APT
  • Estimated reading time: 20 minutes

Introduction

Linux follows the Unix philosophy: small, focused tools that do one thing well and can be combined through pipes to accomplish complex tasks. Text processing is at the heart of Linux administration — from parsing log files to transforming configuration data.

In this lesson, you will master the essential text processing tools (grep, sed, awk) and learn how to write bash scripts to automate repetitive tasks. These skills will dramatically increase your productivity as a system administrator.

grep — Search Text with Patterns

grep searches for patterns in text and prints matching lines:

$ grep "error" /var/log/syslog            # Find lines containing "error"
$ grep -i "error" /var/log/syslog         # Case-insensitive search
$ grep -r "listen" /etc/nginx/            # Recursive search in directory
$ grep -n "root" /etc/passwd              # Show line numbers
1:root:x:0:0:root:/root:/bin/bash

$ grep -c "Failed" /var/log/auth.log     # Count matching lines
42

$ grep -v "^#" /etc/ssh/sshd_config      # Exclude comment lines
$ grep -E "error|warning|critical" /var/log/syslog  # Extended regex (egrep)

Common regex patterns with grep:

  • ^ — Beginning of line
  • $ — End of line
  • . — Any single character
  • .* — Any number of any characters
  • [0-9] — Any digit

sed — Stream Editor

sed transforms text line by line. The most common operation is search-and-replace:

$ sed 's/old/new/' file.txt               # Replace first occurrence per line
$ sed 's/old/new/g' file.txt              # Replace all occurrences (global)
$ sed -i 's/old/new/g' file.txt           # Edit file in-place
$ sed -i.bak 's/old/new/g' file.txt      # In-place with backup

$ sed -n '5,10p' file.txt                 # Print lines 5 through 10
$ sed '/^#/d' config.txt                  # Delete comment lines
$ sed '3iNew line here' file.txt         # Insert text before line 3
$ sed 's/^/    /' file.txt                # Add 4 spaces to beginning of each line

awk — Pattern Processing

awk is a powerful tool for processing structured, column-based text:

$ awk '{print $1}' /etc/passwd            # Print first field (default separator: space)
$ awk -F: '{print $1, $3}' /etc/passwd    # Use colon as delimiter
root 0
daemon 1
admin 1000

$ awk -F: '$3 >= 1000 {print $1}' /etc/passwd   # Users with UID >= 1000
admin
john

$ df -h | awk 'NR>1 {print $5, $6}'      # Disk usage percentage and mount point
15% /
45% /home
2%  /boot

$ awk '{sum+=$1} END {print sum}' numbers.txt    # Sum a column

Pipes and Redirection

Pipes (|) connect the output of one command to the input of another. Redirection (>, >>) sends output to files:

$ cat /var/log/auth.log | grep "Failed" | wc -l
42

$ ps aux | sort -k3 -rn | head -5        # Top 5 CPU-consuming processes

$ echo "Hello" > file.txt                 # Write (overwrite) to file
$ echo "World" >> file.txt                # Append to file
$ cat file.txt
Hello
World

$ command 2> errors.log                   # Redirect stderr to file
$ command > output.log 2>&1               # Redirect both stdout and stderr
$ command > /dev/null 2>&1                # Discard all output

Bash Scripting

Script Basics

#!/bin/bash
# My first script - save as myscript.sh

NAME="Admin"
echo "Hello, $NAME!"
echo "Today is $(date +%Y-%m-%d)"
echo "You are logged in as: $(whoami)"
echo "Current directory: $(pwd)"
$ chmod +x myscript.sh
$ ./myscript.sh
Hello, Admin!
Today is 2024-01-15
You are logged in as: admin
Current directory: /home/admin

Conditionals and Loops

#!/bin/bash
# Check if a service is running

SERVICE="nginx"

if systemctl is-active --quiet "$SERVICE"; then
    echo "$SERVICE is running"
else
    echo "$SERVICE is NOT running, starting it..."
    sudo systemctl start "$SERVICE"
fi

# Loop through log files
for logfile in /var/log/*.log; do
    lines=$(wc -l < "$logfile")
    echo "$logfile: $lines lines"
done

# While loop - monitor disk usage
while true; do
    usage=$(df / | awk 'NR==2 {print $5}' | tr -d '%')
    if [ "$usage" -gt 90 ]; then
        echo "WARNING: Disk usage is ${usage}%!"
    fi
    sleep 60
done

Functions and Exit Codes

#!/bin/bash

log_message() {
    local level="$1"
    local message="$2"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $message"
}

check_root() {
    if [ "$(id -u)" -ne 0 ]; then
        log_message "ERROR" "This script must be run as root"
        exit 1
    fi
}

check_root
log_message "INFO" "Script started"

apt update > /dev/null 2>&1
if [ $? -eq 0 ]; then
    log_message "INFO" "Package lists updated successfully"
else
    log_message "ERROR" "Failed to update package lists"
    exit 2
fi

Key Takeaways

  • grep searches for patterns in text; use -i for case-insensitive, -r for recursive, -E for extended regex.
  • sed transforms text streams; s/old/new/g is the most common pattern. Use -i for in-place edits.
  • awk processes columnar data; use -F to set the field delimiter.
  • Pipes (|) chain commands together; > overwrites files, >> appends, 2>&1 merges stderr into stdout.
  • Bash scripts start with #!/bin/bash, use variables with $, and support conditionals, loops, and functions.
  • Exit codes indicate success (0) or failure (non-zero); check with $?.

What’s Next

In Lesson 8, you will learn about Storage and Logical Volume Management — how to work with block devices, filesystems, mount points, and LVM.

繁體中文

概述

  • 學習目標:學習如何使用 grep、sed、awk 處理文字,使用管道和重導向,以及編寫 bash shell 腳本。
  • 先決條件:第 6 課 – 使用 APT 的套件管理
  • 預計閱讀時間:20 分鐘

簡介

Linux 遵循 Unix 哲學:小巧、專注的工具各自做好一件事,並可透過管道組合完成複雜任務。文字處理是 Linux 管理的核心——從解析日誌檔案到轉換設定資料。

grep — 以模式搜尋文字

$ grep "error" /var/log/syslog            # 尋找包含 "error" 的行
$ grep -i "error" /var/log/syslog         # 不區分大小寫
$ grep -r "listen" /etc/nginx/            # 在目錄中遞迴搜尋
$ grep -c "Failed" /var/log/auth.log     # 計算匹配行數
$ grep -E "error|warning" /var/log/syslog # 擴充正規表示式

sed — 串流編輯器

$ sed 's/old/new/g' file.txt              # 替換所有出現的字串
$ sed -i 's/old/new/g' file.txt           # 直接編輯檔案
$ sed -n '5,10p' file.txt                 # 列印第 5 到 10 行
$ sed '/^#/d' config.txt                  # 刪除註解行

awk — 模式處理

$ awk -F: '{print $1, $3}' /etc/passwd    # 使用冒號作為分隔符
$ awk -F: '$3 >= 1000 {print $1}' /etc/passwd   # UID >= 1000 的使用者
$ df -h | awk 'NR>1 {print $5, $6}'      # 磁碟使用率和掛載點

管道和重導向

$ cat /var/log/auth.log | grep "Failed" | wc -l  # 管道組合命令
$ echo "Hello" > file.txt                 # 寫入(覆寫)檔案
$ echo "World" >> file.txt                # 附加到檔案
$ command > /dev/null 2>&1                # 捨棄所有輸出

Bash 腳本

腳本基礎

#!/bin/bash
NAME="Admin"
echo "Hello, $NAME!"
echo "Today is $(date +%Y-%m-%d)"

條件和迴圈

#!/bin/bash
if systemctl is-active --quiet "nginx"; then
    echo "nginx 正在運行"
else
    echo "nginx 未運行,正在啟動..."
    sudo systemctl start nginx
fi

for logfile in /var/log/*.log; do
    lines=$(wc -l < "$logfile")
    echo "$logfile: $lines 行"
done

函式和退出碼

退出碼表示成功 (0) 或失敗(非零值);使用 $? 檢查。

重點摘要

  • grep 搜尋文字模式;-i 不區分大小寫,-r 遞迴搜尋,-E 擴充正規表示式。
  • sed 轉換文字串流;s/old/new/g 是最常見的模式。
  • awk 處理欄位資料;-F 設定欄位分隔符。
  • 管道 (|) 串連命令;> 覆寫,>> 附加,2>&1 合併標準錯誤。
  • Bash 腳本以 #!/bin/bash 開頭,支援條件、迴圈和函式。

下一步

在第 8 課中,您將學習儲存和邏輯卷管理——如何使用區塊裝置、檔案系統、掛載點和 LVM。

日本語

概要

  • 学習内容:grep、sed、awk によるテキスト処理、パイプとリダイレクション、bash シェルスクリプトの作成。
  • 前提条件:レッスン6 – APT によるパッケージ管理
  • 推定読了時間:20分

はじめに

Linux は Unix の哲学に従っています:小さく焦点を絞ったツールがそれぞれ一つのことをうまくこなし、パイプを通じて組み合わせることで複雑なタスクを達成できます。テキスト処理は Linux 管理の中心にあります。

grep — パターンでテキストを検索

$ grep "error" /var/log/syslog            # "error" を含む行を検索
$ grep -i "error" /var/log/syslog         # 大文字小文字を区別しない
$ grep -r "listen" /etc/nginx/            # ディレクトリ内を再帰的に検索
$ grep -c "Failed" /var/log/auth.log     # マッチする行数をカウント
$ grep -E "error|warning" /var/log/syslog # 拡張正規表現

sed — ストリームエディタ

$ sed 's/old/new/g' file.txt              # すべての出現箇所を置換
$ sed -i 's/old/new/g' file.txt           # ファイルを直接編集
$ sed -n '5,10p' file.txt                 # 5行目から10行目を表示
$ sed '/^#/d' config.txt                  # コメント行を削除

awk — パターン処理

$ awk -F: '{print $1, $3}' /etc/passwd    # コロンを区切り文字として使用
$ awk -F: '$3 >= 1000 {print $1}' /etc/passwd   # UID >= 1000 のユーザー
$ df -h | awk 'NR>1 {print $5, $6}'      # ディスク使用率とマウントポイント

パイプとリダイレクション

$ cat /var/log/auth.log | grep "Failed" | wc -l  # パイプでコマンドを連結
$ echo "Hello" > file.txt                 # ファイルに書き込み(上書き)
$ echo "World" >> file.txt                # ファイルに追記
$ command > /dev/null 2>&1                # すべての出力を破棄

Bash スクリプト

スクリプトの基本

#!/bin/bash
NAME="Admin"
echo "Hello, $NAME!"
echo "Today is $(date +%Y-%m-%d)"

条件分岐とループ

#!/bin/bash
if systemctl is-active --quiet "nginx"; then
    echo "nginx は実行中です"
else
    echo "nginx は実行されていません。起動します..."
    sudo systemctl start nginx
fi

for logfile in /var/log/*.log; do
    lines=$(wc -l < "$logfile")
    echo "$logfile: $lines 行"
done

関数と終了コード

終了コードは成功 (0) または失敗(0以外)を示します。$? で確認できます。

重要ポイント

  • grep はテキストパターンを検索。-i で大文字小文字を無視、-r で再帰的、-E で拡張正規表現。
  • sed はテキストストリームを変換。s/old/new/g が最も一般的なパターン。
  • awk はカラムデータを処理。-F でフィールド区切り文字を設定。
  • パイプ (|) でコマンドを連結。> は上書き、>> は追記、2>&1 で stderr を統合。
  • Bash スクリプトは #!/bin/bash で始まり、条件分岐、ループ、関数をサポート。

次のステップ

レッスン8では、ストレージと論理ボリューム管理について学びます。ブロックデバイス、ファイルシステム、マウントポイント、LVM の使い方を学びます。

You Missed