Unix

在 Unix shell 中提取子字元串的最簡單方法?

  • April 18, 2018

在 Unix shell(使用正則表達式)上提取子字元串的最簡單方法是什麼?

簡單的意思:

  • 較少的功能
  • 更少的選擇
  • 少學習

更新

我意識到正則表達式本身與簡單性相衝突,因此我選擇了最簡單的一個cut作為選擇的答案。對於含糊的問題,我很抱歉。我更改了標題以更準確地表示此 QA 的目前狀態。

cut可能有用:

$ echo hello | cut -c1,3
hl
$ echo hello | cut -c1-3
hel
$ echo hello | cut -c1-4
hell
$ echo hello | cut -c4-5
lo

Shell Builtins 也適用於此,這是一個範例腳本:

#!/bin/bash
# Demonstrates shells built in ability to split stuff.  Saves on
# using sed and awk in shell scripts. Can help performance.

shopt -o nounset
declare -rx       FILENAME=payroll_2007-06-12.txt

# Splits
declare -rx   NAME_PORTION=${FILENAME%.*}     # Left of .
declare -rx      EXTENSION=${FILENAME#*.}     # Right of .
declare -rx           NAME=${NAME_PORTION%_*} # Left of _
declare -rx           DATE=${NAME_PORTION#*_} # Right of _
declare -rx     YEAR_MONTH=${DATE%-*}         # Left of _
declare -rx           YEAR=${YEAR_MONTH%-*}   # Left of _
declare -rx          MONTH=${YEAR_MONTH#*-}   # Left of _
declare -rx            DAY=${DATE##*-}        # Left of _

clear

echo "  Variable: (${FILENAME})"
echo "  Filename: (${NAME_PORTION})"
echo " Extension: (${EXTENSION})"
echo "      Name: (${NAME})"
echo "      Date: (${DATE})"
echo "Year/Month: (${YEAR_MONTH})"
echo "      Year: (${YEAR})"
echo "     Month: (${MONTH})"
echo "       Day: (${DAY})"

輸出:

 Variable: (payroll_2007-06-12.txt)
 Filename: (payroll_2007-06-12)
Extension: (txt)
     Name: (payroll)
     Date: (2007-06-12)
Year/Month: (2007-06)
     Year: (2007)
    Month: (06)
      Day: (12)

根據上面的 Gnudif,當事情變得非常艱難時,總會有 sed/awk/perl。

引用自:https://serverfault.com/questions/178101