Toy*_*der 167
如果您正在寻找shell实用程序来执行类似的操作,则可以使用该cut命令.
举个例子,试试:
echo "abcdefg" | cut -c3-5
Run Code Online (Sandbox Code Playgroud)
产量
cde
Run Code Online (Sandbox Code Playgroud)
凡-cN-M告诉剪切命令列返回N到M,包容性.
dmc*_*kee 95
从bash手册页:
${parameter:offset}
${parameter:offset:length}
Substring Expansion. Expands to up to length characters of
parameter starting at the character specified by offset.
[...]
Run Code Online (Sandbox Code Playgroud)
或者,如果您不确定bash,请考虑使用cut.
ata*_*ata 34
在"纯"bash中,你有很多用于(子)字符串操作的工具,主要是但不仅仅是参数扩展:
${parameter//substring/replacement}
${parameter##remove_matching_prefix}
${parameter%%remove_matching_suffix}
Run Code Online (Sandbox Code Playgroud)
索引子字符串扩展(具有负偏移的特殊行为,以及在较新的Bashes中,负长度):
${parameter:offset}
${parameter:offset:length}
${parameter:offset:length}
Run Code Online (Sandbox Code Playgroud)
当然,对参数是否为null进行操作的非常有用的扩展:
${parameter:+use this if param is NOT null}
${parameter:-use this if param is null}
${parameter:=use this and assign to param if param is null}
${parameter:?show this error if param is null}
Run Code Online (Sandbox Code Playgroud)
它们具有比列出的行为更多的可调整行为,正如我所说,还有其他方法来操纵字符串(一种常见的方法是$(command substitution)与sed或任何其他外部过滤器结合).但是,通过打字很容易找到它们man bash,我觉得进一步扩展这篇文章并不值得.
Jua*_*nma 19
在bash中你可以试试这个:
stringZ=abcABC123ABCabc
# 0123456789.....
# 0-based indexing.
echo ${stringZ:0:2} # prints ab
Run Code Online (Sandbox Code Playgroud)
cam*_*amh 13
expr(1) 有一个substr子命令:
expr substr <string> <start-index> <length>
Run Code Online (Sandbox Code Playgroud)
如果您没有bash(可能是嵌入式Linux)并且您不希望使用cut(1)需要额外的"echo"过程,这可能很有用.