1

my log.txt file includes

...
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
...

how can I replace

mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128

with

mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 0.0.0.0/0  

from the command Line? In other words, I want to add 0.0.0.0/0 to the end of that line.

1

To add the specified text to a line in the file - if that line is the only one that starts with mynetworks, you can do this:

sed --in-place '/^mynetworks/s_.*_& 0.0.0.0/0_' /path/to/file
3

Using sed

sed -i 's+^mynetworks.*+& 0.0.0.0/0+' log.txt

Using awk

awk '/^mynetworks/ {$0=$0" 0.0.0.0/0"} 1' log.txt

or

awk '{if ($1 ~ /^mynetworks/) print $0, "0.0.0.0/0"; else print $0}' log.txt

Using bash

while read -r line ; do
    [[ $line == mynetworks* ]] && line+=" 0.0.0.0/0"
    echo "$line"
done < log.txt
  • 1
    That will add 0.0.0.0/0 to every line in the file. – DopeGhoti Jun 21 '16 at 5:51
  • log.txt include many lines , i want awk add end of this line mynetworks = – Mehran Goudarzi Jun 21 '16 at 5:52
  • @MehranGoudarzi see my updates – Rahul Jun 21 '16 at 5:57
  • @DopeGhoti yeah, actually I misunderstood requirements. thanks – Rahul Jun 21 '16 at 6:06
  • 3
    There's no point in using g when you're anchoring the regex to the beginning of the line (^). In any case, the g will make sed replace every occurrence in each line, not "globally in the file", but "globally on the line". It is only useful if you expect more than one match per line, not more than one per file (that's what sed does anyway). – terdon Jun 21 '16 at 9:24
0

I tend to use Perl. sed or awk is fine in this case, but sometimes the flexibility is Perl is useful.

perl -pi -e 's/^(mynetworks.*)/$1 0.0.0.0\/0/' /path/to/file

or if this is in a pipe chain

cat file | perl -pe 's/^(mynetworks.*)/$1 0.0.0.0\/0/'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.