简体   繁体   中英

Bash: How to count number of lines in a section, increment it and add another line

I have two files and a path variable:

path=$1

file1:

[usera:pathlist]
1=/path
2=/another/path

[userb:pathlist]
1=/path
2=/another/path
3=/one/more/path

[userc:pathlist]
1=/path

file2:

usera
userc

I need a script to add $path to all users in file1 if they exist in file2 and raise the linecount by one.

The result should then look like this:

file1:

[usera:pathlist]
1=/path
2=/another/path
3=$path

[userb:pathlist]
1=/path
2=/another/path
3=/one/more/path

[userc:pathlist]
1=/path
2=$path

Unfortunately i don't have enough experience with sed and didn't use awk yet. Or maybe there is another tool that suits my needs better? I would be really grateful if you could lead me into the right direction here. Thank you very much.

Udpdate#1:

[usera:pathlist]
1=/path
2=/another/path
1=$path

[userb:pathlist]
1=/path
2=/another/path
3=/one/more/path

[userc:pathlist]
1=/path
1=$path
awk -v path="$path" '
  FNR==NR{ u[$1]; next }
  FNR > 1{ print "" }
  {
    add=0
    for (user in u) 
      if ($1 ~ "^\\[" user ":"){ add=1; break }
  }
  1
  add{ print NF "=" path }
' file2 RS="" file1

another awk

$ awk -v p='$path' -v ORS='\n\n' -v OFS='\n' 'NR==FNR{a["["$1]; next}
                                                     {split($1,u,":")} 
                                           u[1] in a {$(NF+1)=NF"="p}1' file2 RS= file1

[usera:pathlist]
1=/path
2=/another/path
3=$path

[userb:pathlist]
1=/path
2=/another/path
3=/one/more/path

[userc:pathlist]
1=/path
2=$path

to use the value of $path instead of the literal $path change single quotes with double quotes in the definition of p variable. Note that RS value set between files.

perhaps this is simpler

$ awk -v p='$path' 'NR==FNR{a["["$1]; next} 
                           {split($1,u,":"); 
                            print $0 ORS (u[1] in a?NF"="p:"") ORS}' file2 RS= file1 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM