Как я могу отфильтровать уникальные строки на основе подстроки?

350
jhamburg

Если у меня есть набор URL-адресов в файле, как:

http://example.com/do?foo=bar&etc=123

http://example.com/do?etc=456&foo=bar

Я хочу отфильтровать это так, чтобы для каждого уникального значения параметра 'foo' был только один URL. Остальная часть URL не имеет значения, для меня важно только то, что у меня нет двух или более строк с одинаковым значением «foo».

-1
Что вы пробовали? Где ты потерпел неудачу? Это не сайт для написания сценариев, мы только советуем людям, как исправлять ошибки, с которыми они сталкиваются. MariusMatutiae 8 лет назад 1

1 ответ на вопрос

0
Gombai Sándor

Since you tagged the question with awk, I guess you are familiar with it at some level, for example you know that you can set the field separator to a set of characters at the command line (and elsewhere) like -F'[?&]'.

Also, you may know that the NF variable contains the number of the fields parsed in the current input record (line) and you can loop from 2 to NF with a C-style for(...;...;...) to find the foo=xxx field.

And the best thing that can serve you here is the associative array of awk (called dictionary or hash or map in other contexts) in which you can store a value in the index and check if a value is already in the array as an index and make decisions accordingly. Such as:

if ( ! (value in myarray) ) { print thelinevalueisfrom myarray[value] = 1 # just to register we have seen value for later usage } 

Basically, this is all you need here.

Похожие вопросы