免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12下一页
最近访问板块 发新帖
查看: 5767 | 回复: 12
打印 上一主题 下一主题

[网络管理] shell中如何截取指定个数的字符串 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-05-15 19:12 |只看该作者 |倒序浏览
我有一串字符串,我想截取Intel Corporation存到一个变量,Intel Corporation 以后的部分存到另一个变量,前面的都不要,请问该怎么做,下面是整个字符串
3f:06.3 Host bridge: Intel Corporation Xeon 5500/Core i7 Integrated Memory Controller Channel 2 Thermal Control Registers (rev 05)

论坛徽章:
0
2 [报告]
发表于 2012-05-16 07:57 |只看该作者
yuexiaduzhuo_cu 发表于 2012-05-15 19:12
我有一串字符串,我想截取Intel Corporation存到一个变量,Intel Corporation 以后的部分存到另一个变量,前 ...

这个问题可以用cut命令解决(但它是不稳定的),方法如下:
$ cat > string.txt
3f:06.3 Host bridge: Intel Corporation Xeon 5500/Core i7 Integrated Memory Controller Channel 2 Thermal Control Registers (rev 05)
$ A=$(cut -d ' ' -f 7- string.txt)
$ B=$(cut -d ' ' -f 4-5 string.txt)
$ echo $A
5500/Core i7 Integrated Memory Controller Channel 2 Thermal Control Registers (rev 05)
$ echo $B
Intel Corporation

论坛徽章:
0
3 [报告]
发表于 2012-05-16 08:34 |只看该作者
可以了,非常感谢,可以告诉我那个7-和4-5是什么意思吗,我琢磨半天,好像不是字符串的位置啊回复 2# zjhxmjl


   

论坛徽章:
0
4 [报告]
发表于 2012-05-16 08:38 |只看该作者
还有,为什么说他不稳定呢回复 2# zjhxmjl


   

论坛徽章:
1
2015年辞旧岁徽章
日期:2015-03-03 16:54:15
5 [报告]
发表于 2012-05-16 08:50 |只看该作者
  1. $ echo "3f:06.3 Host bridge: Intel Corporation Xeon 5500/Core i7 Integrated Memory Controller Channel 2 Thermal Control Registers (rev 05)" | grep -o "Intel Corporation"
  2. Intel Corporation
复制代码
  1. $ echo "3f:06.3 Host bridge: Intel Corporation Xeon 5500/Core i7 Integrated Memory Controller Channel 2 Thermal Control Registers (rev 05)" | sed 's/^.*Intel Corporation//'
  2. Xeon 5500/Core i7 Integrated Memory Controller Channel 2 Thermal Control Registers (rev 05)
复制代码

论坛徽章:
0
6 [报告]
发表于 2012-05-16 09:13 |只看该作者
可能是我描述的有些问题,我事先不知道这串字符,我是想获取网卡的硬件信息,然后截取他的厂商和后面的参数,这串字符是我用lspci命令列出来的回复 5# L_kernel


   

论坛徽章:
0
7 [报告]
发表于 2012-05-16 09:47 |只看该作者
回复 3# yuexiaduzhuo_cu


    cut -d ' ' -f 4-5 string.txt
-d指定以' '(也就是空格) 来分割字符串为字段,4-5是取出第四和第五个字段而不是你说的字符

论坛徽章:
0
8 [报告]
发表于 2012-05-16 09:57 |只看该作者
回复 5# L_kernel


牛人

论坛徽章:
0
9 [报告]
发表于 2012-05-16 11:39 |只看该作者
本帖最后由 zjhxmjl 于 2012-05-16 12:55 编辑
yuexiaduzhuo_cu 发表于 2012-05-16 08:38
还有,为什么说他不稳定呢回复 2# zjhxmjl

说它不稳定是因为cut只擅长处理以一个字符间隔的文本,如果某些域以若干个空格间隔,cut就很麻烦了!参考资料

论坛徽章:
33
ChinaUnix元老
日期:2015-02-02 08:55:39CU十四周年纪念徽章
日期:2019-08-20 08:30:3720周年集字徽章-周	
日期:2020-10-28 14:13:3020周年集字徽章-20	
日期:2020-10-28 14:04:3019周年集字徽章-CU
日期:2019-09-08 23:26:2519周年集字徽章-19
日期:2019-08-27 13:31:262016科比退役纪念章
日期:2022-04-24 14:33:24
10 [报告]
发表于 2012-05-19 06:07 |只看该作者
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP