简体   繁体   English

从Bash中的字符串中提取字符串

[英]Extract string from string in Bash

The script reads in lines from a text file. 该脚本从文本文件中逐行读取。 A line looks like this. 一条线看起来像这样。

227 A S  comment=comment string dst-address=9.9.9.9/29 gateway=192.168.199.2 gateway-status=192.168.199.2 reachable via  LACP1=1 scope=30 target-scope=10

This is assigned the variable $route 这分配了变量$ route

I then need to then assign 9.9.9.9/29 as the variable $subnet . 然后,我需要将9.9.9.9/29分配为变量$subnet I can't use awk because the column position of dst-address will vary in the lines. 我不能使用awk因为dst-address的列位置在行中会有所不同。

To recap I need to search each line for " dst-address= " and then assign the string after the '=' to the variable $subnet. 回顾一下,我需要在每一行中搜索“ dst-address= ”,然后将'='之后的字符串分配给变量$ subnet。

My ideal solution is 我理想的解决方案是

while read routes ; do
    subnet=< code I need >
done < /tmp/routingTable.txt

Perl解决方案:

perl -n -e'/dst-address=(\S+)/ && print $1."\n"' your_file

一个无循环的bash解决方案

echo $route | sed -r "s/.*dst-address=([0-9./]+).*/\1/"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM