Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all lines in file with specific regex using sed

Tags:

regex

bash

sed

We'd like to delete all lines which matches with the following "regex input" and put them in a new file:

Hi|thisisatest|11

What we have:

check='([^[:space:]]+)|([^[:space:]]+)|([^[:space:]]+)'
sed '/$check/d' test.txt > test_new.txt

It currently does not work.

Edit:

We got the following test.txt:

Jack|Miles|44
Carl|13
Robert|Whittaker|87
John|2
Frank|65

We want to delete Jack|Miles|44 and Robert|Whittaker|87, which matches the regex (if the regex is correct).

like image 681
Frank Stone Avatar asked Dec 13 '25 13:12

Frank Stone


2 Answers

Correct BRE regex is:

check='[^[:space:]]*|[^[:space:]]*|[^[:space:]]*'

Then use it as:

sed "/$check/d" file
Carl|13
John|2
Frank|65

btw awk can handle it even better without using regex. Just use | as delimiter and delete all line that don't have 2 fields:

awk -F '|' 'NF==2' file

Carl|13
John|2
Frank|65
like image 67
anubhava Avatar answered Dec 15 '25 16:12

anubhava


It is much more simpler when using awk, just do,

awk -F'|' 'NF<=2' file
Carl|13
John|2
Frank|65

To modify the same file back with the updates, just do,

awk -F'|' 'NF<=2' file > tmp && mv tmp file
like image 20
Inian Avatar answered Dec 15 '25 15:12

Inian