如何删除特定字符后的字符串中的所有内容? [英] How to delete everything in a string after a specific character?

查看:98
本文介绍了如何删除特定字符后的字符串中的所有内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:

    before: text_before_specific_character(specific_character)text_to_be_deleted
    after: text_before_specific_character

我知道可以用'sed'完成.但是我被困住了.有人可以帮我吗?

I know that it can be done with 'sed'. But i'm stuck. Can someone help me out?

推荐答案

没有理由为此使用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.

这篇关于如何删除特定字符后的字符串中的所有内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆