awk - Append a string after a multiple line match in bash -


i need sed or awk command print line after multiple line match in bash. example having file input:

admin:   users:     - user1     - user2  read_only:   users:     - user3  write_only:   users:     - user4  access_only:   users:     - user5     - user6 

..i need have output:

admin:   users:     new user     - user1     - user2  read_only:   users:     - user3  write_only:   users:     - user4  access_only:   users:     - user5     - user6 

the regex should match first 2 lines admin: users: , append new user line.

how this? should use sed or awk? how? thank you

with sed

delimit block between /^[a-z_]\+:/ , /^$/, somme process in 1 block:

sed -e $'/^admin:/,/^$/{/users:/a\    newuser\n}' 

this written:

newuser="user2017" sed -e "/^admin:/,/^$/{     /users:/a\    - $newuser }" 

(by using double quotes, use variable commandline or script)

this render:

admin:   users:     - user2017     - user1     - user2  read_only:   users:     - user3  ... 

or pure ...

myadduser () {      local crt= line;     while ifs= read line;         echo "$line";         [ "$line" ] && {              [ "${line:0:1}" != " " ] && crt=${line%:} || {                  [ "${line//*([: ])}" = "users" ] &&                     [ "$crt" = "${2:-admin}" ] &&                         printf "    - %s\n" $1             }         };     done } 

which used:

myadduser newadminuser <file.txt admin:   users:     - newadminuser     - user1     - user2  read_only:   users:     - user3  ... 

or optional second argument:

myadduser newwriteuser write_only admin:   users:     - user1     - user2  read_only:   users:     - user3  write_only:   users:     - newwriteuser     - user4  access_only:   users:     - user5     - user6 

but please,

read sobrique's fine answer!

with or prototyping using finalized programmation, may find apropriate libraries.

using of libraries in done too.

1st admin user
perl -myaml -e 'undef$/;$s = load(<>);say@{$s->{admin}->{users}}[0];' 
count of admin users
perl -myaml -e 'undef$/;$s = load(<>);say scalar@{$s->{admin}->{users}};'  

Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -