How to add text with sed at the end-of-line minus 1 position

Viewed 225

I want to add the text [*,test,*] just before the last character of a line starting with resourceFilters: in the input file (that string can be preceded by any number of spaces).

An example of this line is the following

resourceFilters: '[Event,*,*][*,kube-system,*][*,kube-public,*][*,kube-node-lease,*][Node,*,*][APIService,*,*][TokenReview,*,*][SubjectAccessReview,*,*][Binding,*,*][ReplicaSet,*,*]'

which would be changed into this:

resourceFilters: '[Event,*,*][*,kube-system,*][*,kube-public,*][*,kube-node-lease,*][Node,*,*][APIService,*,*][TokenReview,*,*][SubjectAccessReview,*,*][Binding,*,*][ReplicaSet,*,*][*,test,*]'
2 Answers
sed "/^ *resourceFilters: '/s/'$/[*,test,*]'/" your_file
  • I've double quoted the Sed command so that I can use single quotes in it;
  • /^resourceFilters: '/ makes the following substitution command only act on lines starting with resourceFilters: ';
  • s/'$/[*,test,*]'/ is the substitution command which matches ' at end of line ($), and substitutes [*, test,*]' to it, effectively inserting [*,test,*] before the '.

This might work for you (GNU sed):

sed -E 's/^(\s*resourceFilters:.*)(.)$/\1[*,test,*]\2/' file

Match on a line containing resourceFilters: and insert [*,test,*] before the last character of the line.

Related