for*_*sck 52
在带有“参数扩展”的 bash 中 ${parameter:offset:length}
$ var=abcdef
$ echo ${var:0:1}
a
$ echo ${var:3:1}
d
Run Code Online (Sandbox Code Playgroud)
可以使用相同的参数扩展来分配新变量:
$ x=${var:1:1}
$ echo $x
b
Run Code Online (Sandbox Code Playgroud)
编辑:没有参数扩展(不是很优雅,但这就是我首先想到的)
$ charpos() { pos=$1;shift; echo "$@"|sed 's/^.\{'$pos'\}\(.\).*$/\1/';}
$ charpos 8 what ever here
r
Run Code Online (Sandbox Code Playgroud)
dog*_*ane 11
参数扩展的替代方法是 expr substr
substr STRING POS LENGTH
substring of STRING, POS counted from 1
Run Code Online (Sandbox Code Playgroud)
例如:
$ expr substr hello 2 1
e
Run Code Online (Sandbox Code Playgroud)
cut -c
如果变量不包含换行符,您可以执行以下操作:
myvar='abc'
printf '%s\n' "$myvar" | cut -c2
Run Code Online (Sandbox Code Playgroud)
输出:
b
Run Code Online (Sandbox Code Playgroud)
awk substr
是另一种 POSIX 替代方案,即使变量有换行符也能正常工作:
myvar="$(printf 'a\nb\n')" # note that the last newline is stripped by
# the command substitution
awk -- 'BEGIN {print substr (ARGV[1], 3, 1)}' "$myvar"
Run Code Online (Sandbox Code Playgroud)
输出:
b
Run Code Online (Sandbox Code Playgroud)
printf '%s\n'
是为了避免转义字符出现问题:https : //stackoverflow.com/a/40423558/895245例如:
myvar='\n'
printf '%s\n' "$myvar" | cut -c1
Run Code Online (Sandbox Code Playgroud)
输出\
如预期。
另见:https : //stackoverflow.com/questions/1405611/extracting-first-two-characters-of-a-string-shell-scripting
在 Ubuntu 19.04 中测试。
归档时间: |
|
查看次数: |
117261 次 |
最近记录: |