Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux expr 指令完全攻略:字串操作、整數運算與模式匹配

編輯:關於 Linux

expr 是 Shell 腳本中常用的表達式求值工具,支援整數運算、字串長度、子串擷取、索引查找、模式匹配等功能。本文整理常用語法與實例,可作為命令列計算器與字串處理速查表。

基本語法規則

  • 每個運算元以空格分隔。
  • Shell 特殊字元(如 *、(、))需用反斜線 \ 轉義。
  • 含空格或特殊字元的字串需用雙引號括起。

核心功能與實例

1. 字串長度

expr length "this is a test"
# 14

2. 整數運算

expr 14 % 9        # 餘數 → 5
expr 10 + 10       # 加法 → 20
expr 1000 + 900    # → 1900
expr 30 / 3 / 2    # 除法 → 5
expr 30 \* 3       # 乘法需轉義 → 90
expr 30 * 3        # 錯誤:Syntax error

3. 子串擷取

expr substr "this is a test" 3 5
# 從第 3 字元起取 5 字元 → "is is"

4. 字元索引(首次出現位置)

expr index "testforthegame" e
# e 首次出現於第 2 位 → 2
expr index "sarasara" a
# → 2

5. 字串原樣輸出

expr quote thisisatestformela
# → thisisatestformela

6. 遞增計數器(迴圈常用)

LOOP=0
LOOP=`expr $LOOP + 1`
# 或現代語法:LOOP=$((LOOP+1))

7. 數值測試

rr=3.4
expr $rr + 1
# expr: non-numeric argument

rr=5
expr $rr + 1
# 6

8. 模式匹配(冒號運算子)

VALUE=account.doc
expr $VALUE : '.*'
# 字串長度 → 8

expr $VALUE : '\(.*\)\.doc'
# 擷取 .doc 前的部分 → account

進階應用:腳本片段

#!/bin/bash
# 計算檔名長度
for f in *; do
  len=$(expr length "$f")
  echo "$f : $len"
done

# 擷取副檔名
filename="report.pdf"
ext=$(expr "$filename" : '.*\.\(.*\)')
echo "Extension: $ext"  # pdf

expr 指令實例截圖

小結

expr 雖功能強大,但語法較繁瑣。現代 Bash 推薦使用 $((...)) 整數運算、${#var} 字串長度、${var:offset:length} 子串、[[ $var =~ regex ]] 正則匹配,效能更好且可讀性更高。expr 仍適用於 POSIX sh 相容腳本或嵌入式環境。

Copyright © Windows教程網 All Rights Reserved