简体   繁体   中英

Find multiple strings between values and replace with newline in bash

I need to write a bash script to list values from an sql database.

I've got so far but now I need to get the rest of the way.

The string so far is

10.255.200.0/24";i:1;s:15:"10.255.207.0/24";i:2;s:14:"192.168.0.0/21

I now need to delete everything between the speech marks and send it to a new line.

desired output:

10.255.200.0/24
10.255.207.0/24
192.168.0.0/21

any help would be greatly appreciated.

$ tr '"' '\n' <<< $string | awk 'NR%2'

10.255.200.0/24
10.255.207.0/24
192.168.0.0/21

You could use :

echo 'INPUT STRING HERE' | sed $'s/"[^"]*"/\\\n/g'

Explanation :

  • sed 's/<PATTERN1>/<PATTERN2/g' : we substitute every occurrence of PATTERN1 by PATTERN2
  • [^"]* : any character that is not a " , any number of time
  • \\\\\\n : syntax for newline in sed ( reference here )

Considering that your Input_file is same as shown sample then could you please try following.

awk '
{
  while(match($0,/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+\/[0-9]+/)){
    print substr($0,RSTART,RLENGTH)
    $0=substr($0,RSTART+RLENGTH)
  }
}'   Input_file

This might work for you (GNU sed):

sed 's/"[^"]*"/\n/g' file

Or using along side Bash:

sed $'/"[^"]*"/\\n/g' file

Or using most other sed's:

sed ':a;/"[^"]*"\(.*\)\(.\|$\)/{G;s//\2\1/;ba}' file

This uses the feature that an unadulterated hold space contains a newline.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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