Sed to remove more than 2 words in single line

Viewed 57

I'm asking your help, I want to remove words 'TAGS' , 'Owner' , 'QA' from the txt file . in single sed command , example sed -e 's/\TAGS//g' test.txt and add the email address example John@gmail.com to the end of the line example postgres vp-postgres None default:postgres-13 True stopped db.m6g.large 13.4 vpc-95525af1 John@gmail.com

postgres    vp-postgres None    default:postgres-13 True    stopped db.m6g.large    13.4    vpc-95525af1
TAGS    Owner   John@gmail.com
TAGS        QA
TAGS    autostop    yes
4 Answers

One option could be first matching the line that starts with postgress.

Then pull the next line in the pattern space, and replace the leading TAGS or Owner or QA.

sed -E '/^postgres/{N;s/\n([[:blank:]]*(TAGS|Owner|QA))*//}' file test.txt

Output

postgres    vp-postgres None    default:postgres-13 True    stopped db.m6g.large    13.4    vpc-95525af1   John@gmail.com
TAGS        QA
TAGS    autostop    yes

If you only want that modified line as an output:

sed -En '/^postgres/{N;s/\n([[:blank:]]*(TAGS|Owner|QA))*//;p}' file

Output

postgres    vp-postgres None    default:postgres-13 True    stopped db.m6g.large    13.4    vpc-95525af1   John@gmail.com

Using GNU sed

$ sed -E ':a;N;s/(\n.*)?( [[:alpha:]]+@.*)\n.*/\2/;ba' input_file
postgres    vp-postgres None    default:postgres-13 True    stopped db.m6g.large    13.4    vpc-95525af1 John@gmail.com

You can perform multiple commands in a single invocation of sed:

sed -e s/TAGS//g -e s/Owner//g -e s/QA//g -e '/^postgres/s/$/ John@gmail.com/' test.txt

This might work for you (GNU sed):

sed -E 's/\<(TAGS|Owner|QA)\>//g
        /^postgres    vp-postgres None    default:postgres-13 True    stopped db.m6g.large    13.4    vpc-95525af$/s/$/ John@gmail.com/' file

Us word boundaries and alternation to match words to be removed and match on a complete line to append the required text.

Related