Tuesday, February 1, 2022

[SOLVED] How to delete a line if the occurrence of a string is exactly once per line?

Issue

I need to delete all the lines which contains a string exactly once in the same line. I would keep the line if there is no match found or even if the string matches twice.

I am trying to delete the lines that contain the string "priority" and only when this string appears exactly once per line. Is there anyway to do it using awk or sed ? This command does not give the desired output awk -F'priority' 'NF==1' filename

Input file :

shopping_priority+brands,baby_priority_brands

shopping_priority+brands,baby_shopping_brands

men_shopping_local,women_shopping_local

Expected output:

shopping_priority+brands,baby_priority_brands
men_shopping_local,women_shopping_local

Update: Now I want to check for multiple words instead of "priority" . For example, I also want to check for {priority,women,shopping} and delete the line if "priority" or "women" or "shopping" occurs only once in a line.The list of words to check can be expanded later.

Input:

shopping_priority+brands,baby_priority_brands

shopping_priority+brands,baby_shopping_brands

men_shopping_local,women_shopping_local

pla%20electronics_bfhrg_shopping,pla_electronics_shopping

Now my expected output should be :

pl%20electronics_bfhrg_shopping,pla_electronics_shopping


Solution

This should do:

awk -F"priority" 'NF!=2' file
shopping_priority+brands,baby_priority_brands
men_shopping_local,women_shopping_local

By setting Field Separator to priority, all line with one priority will have two fields. NF!=2 print all lines that do not have one priority



Answered By - Jotne
Answer Checked By - Willingham (WPSolving Volunteer)