bash 如何在bash中从字符串中剪切一些文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1984223/
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-17 21:30:45  来源:igfitidea点击:

How to cut some text from string in bash?

bashstring

提问by bymaker

Bash script

Bash 脚本

I have a string:

我有一个字符串:

tcp 6 0 CLOSE src=111.11.111.111 dst=222.22.222.22 sport=45478 dport=5000 packets=7 bytes=474 src=111.11.111.111 dst=222.22.222.22 s port=5000 dport=45478 packets=8 bytes=550 [ASSURED] mark=0 use=1

tcp 6 0 关闭 src=111.11.111.111 dst=222.22.222.22 运动=45478 dport=5000 数据包=7 字节=474 src=111.11.111.111 dst=222.2225000 字节=222.2250000000000保证] 标记=0 使用=1

I need cut src IP addr 111.11.111.111, how?

我需要把src IP addr 111.11.111.111,怎么做?

回答by scott_karana

Here's a quick and dirty way to do it: Pipe it through sed, like this:

这是一个快速而肮脏的方法:通过 sed 管道它,像这样:

sed -e 's/.*src=\([^ ]*\).*//'

回答by Norman Ramsey

You don't need an external tool for this one. If you're getting the string from a command output, as seems likely, you want

您不需要为此使用外部工具。如果您从命令输出中获取字符串,很可能,您想要

string="$(command)"
string="${string#* src=}"
string="${string%% dst=*}"

First line captures all the output. Second line cuts off the shortest prefix ending in src=. Third line cuts off the longest suffix ending in dst=.

第一行捕获所有输出。第二行切断以src=.结尾的最短前缀。第三行切断以dst=.结尾的最长后缀。

Shell globbing is way easier than regexps!

Shell globbing 比正则表达式容易得多!

回答by ghostdog74

you can use awk. the snippet below gets all src ip, not just one instance of it.

你可以使用awk。下面的代码段获取所有 src ip,而不仅仅是它的一个实例。

<command> | awk '{for(i=1;i<=NF;i++){if($i~/src/){sub("src=","",$i);print $i}}}'