开发者

how to insert next to a line

开发者 https://www.devze.com 2023-02-19 13:32 出处:网络
I have a file in this format machine namehost1 something here1 m开发者_开发技巧achine namehost1 somethingelse2

I have a file in this format

machine name host1

something here1

m开发者_开发技巧achine 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.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号