1

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.

RobC
  • 22,977
  • 20
  • 73
  • 80
noobie01
  • 13
  • 2

4 Answers4

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

10.255.200.0/24
10.255.207.0/24
192.168.0.0/21
karakfa
  • 66,216
  • 7
  • 41
  • 56
1

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)
Aserre
  • 4,916
  • 5
  • 33
  • 56
  • 1
    or via here string: `sed $'s/"[^"]*"/\\\n/g' <<<'10.255.200.0/24";i:1;s:15:"10.255.207.0/24";i:2;s:14:"192.168.0.0/21'` – RobC Oct 10 '18 at 13:41
  • @RobC Indeed. I focused on the sed code in my answer rather than the input method – Aserre Oct 10 '18 at 13:42
  • Whichever method is used (echo with pipe, or here string) the input string will need to be wrapped in single quotes and not double. The OP's string already contains non-escaped double quotes. So `echo 'INPUT STRING HERE' | ...` and not `echo "INPUT STRING HERE" | ...` - as per current answer. – RobC Oct 10 '18 at 13:48
  • @RobC yup, that was an omission on my part. – Aserre Oct 10 '18 at 13:49
1

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
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
0

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.

potong
  • 55,640
  • 6
  • 51
  • 83