string 如何在unix中的特定字符后剪切字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18397698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 02:03:49  来源:igfitidea点击:

How to cut a string after a specific character in unix

stringshellunixsedawk

提问by canecse

So I have this string:

所以我有这个字符串:

[email protected]:/home/some/directory/file

I just want to extract the directory address meaning I only want the bit after the ":" character and get:

我只想提取目录地址,这意味着我只想要“:”字符后面的位并得到:

/home/some/directory/file

thanks.

谢谢。

I need a generic command so the cut command wont work as the $var variable doesn't have a fixed length.

我需要一个通用命令,因此 cut 命令将不起作用,因为 $var 变量没有固定长度。

回答by falsetru

Using sed:

使用 sed:

$ [email protected]:/home/some/directory/file
$ echo $var | sed 's/.*://'
/home/some/directory/file

回答by potong

This might work for you:

这可能对你有用:

echo ${var#*:}

See Example 10-10. Pattern matching in parameter substitution

参见例 10-10。参数替换中的模式匹配

回答by Manish V

This will also do.

这也行。

echo $var | cut -f2 -d":"

回答by chthonicdaemon

For completeness, using cut

为了完整起见,使用 cut

cut -d : -f 2 <<< $var

And using only bash:

并且只使用 bash:

IFS=: read a b <<< $var ; echo $b

回答by Chris Seymour

This should do the trick:

这应该可以解决问题:

$ echo "$var" | awk -F':' '{print $NF}'
/home/some/directory/file

回答by Toby Speight

You don't say which shell you're using. If it's a POSIX-compatible one such as Bash, then parameter expansion can do what you want:

你没有说你使用的是哪个外壳。如果它是 POSIX 兼容的,例如 Bash,那么参数扩展可以做你想做的:

Parameter Expansion

...

${parameter#word}

Remove Smallest Prefix Pattern.
The wordis expanded to produce a pattern. The parameter expansion then results in parameter, with the smallest portion of the prefix matched by the pattern deleted.

参数扩展

...

${parameter#word}

删除最小前缀模式。
word被扩展,以产生一个模式。参数扩展然后导致parameter,与删除模式匹配的前缀的最小部分。

In other words, you can write

换句话说,你可以写

$var="${var#*:}"

which will remove anything matching *:from $var(i.e. everything up to and including the first :). If you want to match up to the last :, then you could use ##in place of #.

这将从中删除任何匹配*:的内容$var(即,直到并包括第一个:)。如果您想匹配到最后一个:,那么您可以使用##代替#

This is all assuming that the part to remove does not contain :(true for IPv4 addresses, but not for IPv6 addresses)

这一切都假设要删除的部分不包含:(适用于 IPv4 地址,但不适用于 IPv6 地址)

回答by Jotne

awk -F: '{print }' <<< $var