在Unix
shell(使用正则表达式)上提取子字符串的最简单方法是什么?
简单意味着:
>减少功能
>减少选择
>少学习
更新
我意识到正则表达式本身与简单性相冲突,我选择了最简单的一个作为选择的答案.对于模糊的问题我很抱歉.我更改了标题以更准确地表示此QA的当前状态.
切割可能有用:
$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,因为什么时候变得非常艰难.