Sed / awk - delete all files except a specific matching pattern from a file

I want to convert a make file as follows:

test.o: var_one.h var_two.h

test2.o: another_header.h var_three.h archive/something_random.h

:

test.o: var_one.h var_two.h

test2.o: var_three.h

those. I want to delete any file name that does not start with the search string "var_"

It seems that I can not find a lot of information for sed about matching patterns, if I do not want a search string?

+3
source share
1 answer

You really need awk for this type of job. With sed, trying to remove words that don't match the string would be a painful (and probably ugly) script to write.

awk '{for(i=2;i<=NF;i++)$i !~ /var_.*\.h/ && $i=""}1' Makefile

Enter

$ cat Makefile
test.o: var_one.h var_two.h

test2.o: another_header.h var_three.h archive/something_random.h

Output

$ awk '{for(i=2;i<=NF;i++)$i !~ /var_.*\.h/ && $i=""}1' Makefile
test.o: var_one.h var_two.h

test2.o:  var_three.h
+2
source

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


All Articles