且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何删除特定字符后的字符串中的所有内容?

更新时间:2023-02-21 13:15:02

没有理由为此使用sed之类的外部工具. bash可以在内部完成,使用参数扩展:

There's no reason to use an external tool such as sed for this; bash can do it internally, using parameter expansion:

如果要修剪的字符是:,例如:

If the character you want to trim after is :, for instance:

$ str=foo_bar:baz
$ echo "${str%%:*}"
foo_bar

您可以用贪​​婪和非贪婪的方式做到这一点:

You can do this in both greedy and non-greedy ways:

$ str=foo_bar:baz:qux
$ echo "${str%:*}"
foo_bar:baz
$ echo "${str%%:*}"
foo_bar

特别是如果您要在一个紧密的循环中调用此函数,启动一个新的sed进程,写入该进程,读取其输出并等待其退出(以获取其PID),则可能是相当大的开销,这是您要做的所有bash内部不会进行处理.

Especially if you're calling this inside a tight loop, starting a new sed process, writing into the process, reading its output, and waiting for it to exit (to reap its PID) can be substantial overhead that doing all your processing internal to bash won't have.

现在-通常,当想要执行此操作时,真正可能想要的是将变量拆分为字段,***使用read来完成.

Now -- often, when wanting to do this, what you might really want is to split a variable into fields, which is better done with read.

例如,假设您正在读取/etc/passwd中的一行:

For instance, let's say that you're reading a line from /etc/passwd:

line=root:x:0:0:root:/root:/bin/bash
IFS=: read -r name password_hashed uid gid fullname homedir shell _ <<<"$line"
echo "$name" # will emit "root"
echo "$shell" # will emit "/bin/bash"


即使您要处理文件中的多行内容,也可以仅使用bash进行操作,而无需外部处理:


Even if you want to process multiple lines from a file, this too can be done with bash alone and no external processes:

while read -r; do
  echo "${REPLY%%:*}"
done <file

...将在file的每一行中发出直到第一个:的所有内容,而无需启动任何外部工具.

...will emit everything up to the first : from each line of file, without requiring any external tools to be launched.