my log.txt file includes

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

how can I replace

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


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

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


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_.*_&' /path/to/file

Using sed

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

Using awk

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


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

Using bash

while read -r line ; do
    [[ $line == mynetworks* ]] && line+=""
    echo "$line"
done < log.txt
  • 1
    That will add 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

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/' /path/to/file

or if this is in a pipe chain

cat file | perl -pe 's/^(mynetworks.*)/$1\/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.