user2266492
user2266492

Reputation: 21

Newlines while saving variable to file - bash

I have mulitiple ip adresses in a variable.

ActiveIPs=192.168.0.1 192.168.0.2 192.168.0.3

I want to save them to a file like this seperated by a newline

192.168.0.1
192.168.0.2
192.168.0.3

how do i do this?

Upvotes: 1

Views: 147

Answers (6)

kojiro
kojiro

Reputation: 77059

Use a parameter expansion to change all space characters to newlines:

$ foo='abc def ghi'
$ echo "${foo// /$'\n'}"
abc
def
ghi

Using a parameter expansion avoids creating a new process altogether, not even a builtin command.

If you can, you'd be better off saving the values into an array:

$ input=( 192.168.0.100 10.0.0.1 192.168.0.101 )

This way, you have complete control over how the shell splits the words, and you still don't have to invoke an external command.

$ SAVE_IFS="$IFS"
$ IFS=$'\n'
$ echo "${input[*]}"
192.168.0.100
10.0.0.1
192.168.0.101

Upvotes: 1

Elmar Peise
Elmar Peise

Reputation: 15413

for ip in $ActiveIPs; do
    echo $ip >> file
done

Upvotes: 1

suspectus
suspectus

Reputation: 17258

Note - Immediately after the \ hit newline-:

echo $ActiveIPs | sed 's/ /\
/g'

Upvotes: 0

Chris Seymour
Chris Seymour

Reputation: 85775

$ ActiveIPs="192.168.0.1 192.168.0.2 192.168.0.3"

$ awk '1' RS=' ' <<< "$ActiveIPs"
192.168.0.1
192.168.0.2
192.168.0.3

Upvotes: 2

chepner
chepner

Reputation: 530950

printf will repeat a pattern as necessary.

ActiveIPs="192.168.0.1 192.168.0.2 192.168.0.3"
printf "%s\n" $ActiveIPs > file.txt

Upvotes: 1

fedorqui
fedorqui

Reputation: 289505

Maybe too basic, but this works:

echo "ActiveIPs= 192.168.0.1 192.168.0.2 192.168.0.3" | cut -d= -f2 | awk '{for (i=1;i<=NF;i++) print $i}'

Output:

192.168.0.1                                                                                                                                                                                                                                                                    
192.168.0.2                                                                                                                                                                                                                                                                    
192.168.0.3

To everyone: is there a better way to print a new line between each field in awk? Tried with OFS='\n' but did not work.

Upvotes: 0

Related Questions