Removing lines from a file that does not match the pattern with sed

I want to delete all lines from a file that has no form:

something.something, something, something

For example, if the file was as follows:

A sentence, some words ABCD.CP3,GHD,HDID Hello. How are you? AB,C,D dbibb.yes,whoami,words 

I would stay with:

 ABCD.CP3,GHD,HDID AB,C,D dbibb.yes,whoami,words 

I tried going to the end of the sed script if I agree with the pattern that I don't want to delete, but continue and delete the line if it doesn't match:

 cp $file{,.tmp} sed "/^.+\..+,.+,.+$/b; /.+/d" "$file.tmp" > $file rm "$file.tmp" 

but this does not seem to have any effect.

I suppose that I could read the file line by line, check if the template matches the template, and output it to the file, if so, but I would like to do it with sed or similar.

+5
source share
3 answers

You can successfully use grep :

 grep -E '^[^.]+\.[^,]+,[^,]+,[^,]+$' file > temp mv temp file 
+4
source
 grep -E '^[^.]+\.[^.]+(,[^,]+){2}$' 
+4
source

Instead of deleting lines that do not match the pattern, you can print lines matching this pattern something.something,something,something .

Via sed,

 $ sed -n '/^[^.]*\.[^,]*,[^,]*,[^,.]*$/p' file ABCD.CP3,GHD,HDID AB,C,D dbibb.yes,whoami,words 

Use the built-in editing function -i[suffix] to save your changes.

 sed -ni.bak '/^[^.]*\.[^,]*,[^,]*,[^,.]*$/p' file 

Note: -i[suffix] backup if provided suffix .

Via awk,

 $ awk '/^[^.]*\.[^,]*,[^,]*,[^,.]*$/{print}' file ABCD.CP3,GHD,HDID AB,C,D dbibb.yes,whoami,words 
+3
source

Source: https://habr.com/ru/post/1200674/


All Articles