webminal.org
webminal.org

Reputation: 47196

how to insert next to a line

I have a file in this format

machine name host1
something here1

machine name host1
somethingelse2

I need to change this as

machine name host1

set username 1000

something here1

machine name host1
set username 1001

somethingelse2

I need find a line "machine name host1" and insert line "set username with incremental-value" on all occurrence next to it.

Upvotes: 0

Views: 80

Answers (2)

Mauritz Hansen
Mauritz Hansen

Reputation: 4774

Using a Perl one-liner (assuming the name of the file with the data is called 'machines':

perl -n -i.bak -e '$i=999 if !$i;
            if (m/machine name host1/) {
               $i++;
               $_ = "$_\nset username $i\n";
            };
            print;' machines

Note that the file itself will be changed and a backup file created with extension .bak

Upvotes: 2

glenn jackman
glenn jackman

Reputation: 246744

awk -v user=1000 '
  {print} 
  /machine name host1/ {printf("set username %d\n", user++)}
' filename

I pass the "seed" value for the user name with awk's -v option

Upvotes: 2

Related Questions