linux 获取前两个字符,如何在Shell脚本中提取字符串的前两个字符?

这篇博客介绍了在Bash shell中如何高效地通过参数扩展来截取字符串的前两个字符,避免了外部程序创建的开销。当需要大量处理字符串时,这种方法优于使用cut、head、awk或sed等外部工具。文章还提到了如何确保字符串的最小长度,并给出了多种使用外部程序截取字符串的替代方案。
摘要由CSDN通过智能技术生成

Probably the most efficient method, if you're using the bash shell (and you appear to be, based on your comments), is to use the sub-string variant of parameter expansion:

pax> long="USCAGol.blah.blah.blah"

pax> short="${long:0:2}" ; echo "${short}"

US

This will set short to be the first two characters of long. If long is shorter than two characters, short will be identical to it.

This in-shell method is usually better if you're going to be doing it a lot (like 50,000 times per report as you mention) since there's no process creation overhead. All solutions which use external programs will suffer from that overhead.

If you also wanted to ensure a minimum length, you could pad it out before hand with something like:

pax> long="A"

pax> tmpstr="${long}.."

pax> short="${tmpstr:0:2}" ; echo "${short}"

A.

This would ensure that anything less than two characters in length was padded on the right with periods (or something else, just by changing the character used when creating tmpstr). It's not clear that you need this but I thought I'd put it in for completeness.

Having said that, there are any number of ways to do this with external programs (such as if you don't have bash available to you), some of which are:

short=$(echo "${long}" | cut -c1-2)

short=$(echo "${long}" | head -c2)

short=$(echo "${long}" | awk '{print substr ($0, 0, 2)}'

short=$(echo "${long}" | sed 's/^\(..\).*/\1/')

The first two (cut and head) are identical for a single-line string - they basically both just give you back the first two characters. They differ in that cut will give you the first two characters of each line and head will give you the first two characters of the entire input

The third one uses the awk sub-string function to extract the first two characters and the fourth uses sed capture groups (using () and \1) to capture the first two characters and replace the entire line with them. They're both similar to cut - they deliver the first two characters of each line in the input.

None of that matters if you are sure your input is a single line, they all have an identical effect.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值