如何在shell脚本中获取字符串给定位置的字符?

The*_*ent 38 shell shell-script

如何在shell脚本中获取字符串给定位置的字符?

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)

  • 虽然这似乎适用于 GNU coreutils 的 expr,但 FreeBSD、NetBSD 或 OS X 的 expr 中不包含 `substr`。这不是一个可移植的解决方案。 (2认同)

Cir*_*郝海东 9

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 中测试。

  • 如果输入不是文本,则“cut”的行为是未指定的(尽管需要“cut”实现来处理行或任意长度)。`printf abc` 的输出不是*文本*,因为它不以换行符结尾。在实践中,根据实现的不同,如果将其通过管道传输到 `cut -c2`,您将得到 `b`、`b<newline>` 或什么也得不到。你需要 `printf 'abc\n' | cut -c2` 以获得 POSIX 指定的行为(输出 `b<newline>` 所需) (2认同)