3

How can I get the results from grep to print on their own line in a bash script?

When using grep in the terminal, the output appears how I wish it would appear.

For instance:

$ whois x.x.85.72 | grep 'OrgName\|NetRange\|inetnum\|IPv4'
NetRange:       x.x.85.64 - x.x.85.95
NetRange:       x.x.0.0 - x.x.255.255
OrgName:        xxxxx Technologies Inc.

When using the same grep command in bash it prints out on one line.

The output of my bash script:

$ lookup xx.com
xx.com resolves to: x.x.85.72
NetRange: x.x.85.64 - x.x.85.95 NetRange: x.x.0.0 - x.x.255.255 OrgName:xxxxx Technologies Inc.

My bash script:

#! /bin/bash
VAR1="$1"

IP=`net lookup $VAR1`
echo $VAR1 resolves to: $IP
RANGE=`whois $IP | grep 'OrgName\|NetRange\|inetnum\|IPv4'`
echo $RANGE 

aside from a solution, can anyone tell me why it does this?

Thanks a bunch!

user2815333
  • 486
  • 1
  • 3
  • 9

4 Answers4

10

You need to quote the variable to have the format preserved:

echo "$RANGE"

instead of

echo $RANGE

All together:

#!/bin/bash <--- be careful, you have an space after ! in your code
VAR1="$1"

IP=$(net lookup $VAR1) #<--- note I use $() rather than ``
echo $VAR1 resolves to: $IP
RANGE=$(whois $IP | grep 'OrgName\|NetRange\|inetnum\|IPv4')
echo "$RANGE"

Example

Given this:

$ date; date
Wed Sep 25 15:18:39 CEST 2013
Wed Sep 25 15:18:39 CEST 2013

Let's print its result with and without quotes:

$ myvar=$(date; date)
$ echo $myvar
Wed Sep 25 15:18:45 CEST 2013 Wed Sep 25 15:18:45 CEST 2013
$ echo "$myvar"
Wed Sep 25 15:18:45 CEST 2013
Wed Sep 25 15:18:45 CEST 2013
fedorqui
  • 275,237
  • 103
  • 548
  • 598
2

Quoting is very important in the shell, you need to quote all your variables to preserve the newlines:

#!/bin/bash

VAR1="$1"

IP=$(net lookup "$VAR1")
echo "$VAR1 resolves to: $IP"
RANGE=$(whois "$IP" | egrep 'OrgName|NetRange|inetnum|IPv4')
echo "$RANGE" 

Read man bash under the quoting section. Also using $() is much clearer than using backticks and it allows nesting.

Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
1

You're missing the quote of the $RANGE variable.

You should use:

echo "$RANGE"

Without the quote the newline isn't preserved.

Atropo
  • 12,231
  • 6
  • 49
  • 62
1

Replace:

RANGE=`whois $IP | grep 'OrgName\|NetRange\|inetnum\|IPv4'`
echo $RANGE 

with

whois $IP | grep 'OrgName\|NetRange\|inetnum\|IPv4'

or

RANGE=`whois $IP | grep 'OrgName\|NetRange\|inetnum\|IPv4'`
echo "$RANGE"
Vlad
  • 1,157
  • 8
  • 15