在 Linux 中,如何根据文本文件中包含的字符显示条目?

问题描述 投票:0回答:1

我尝试过查找,但没有成功。想象一下我有一个包含以下内容的文本文件:

Ray Szeto (416) 564-6786 friend
alex johnson (416) 555-1234 family doctor 
Tom Podstawka (647) 579-3854 dentist
Greg Ivan (905) 789-6703 neighbour
Nikola Sandic (647) 209-7932 friend from work
Tim Yu (416) 570-9522 Jill's coach
Marvin Macalino (416) 570-0983 gym
Paul Jakubiak (647) 097-9257 grocery store
Karim Khalil (905) 346-6892 friend
Denis Malino (416) 098-9259 chiropractor
Timothy Hawn (647) 761-8906 hair dresser
GREGORY FISH (416) 691-9818 Dynasty restaurant
PAUL Demers (647) 123-0987 neighbour
Tara Rathbone (905) 976-1678 babysitter 
ROB Oxley (416) 723-8759 friend from university
Robert Hartzell (647) 190-8630 after-hour children clinic
Stephen Hawn (416) 465-6758 repairman
Steve OXLEYRICH (416) 576-3669 post office
Brenda Caverly (647) 575-5679 babysitter
Sean Zheng (905) 469-1399 neighbour
Ryan ZHENG (416) 678-2488 Lawrence supermaket
Alexander Smith (905) 555-9876 home renovation contractor

...假设我只想在终端中显示名称包含“alex”的条目,不区分大小写。我该怎么做呢?我知道过滤器类似于 %alex% 但我不知道执行此操作的确切命令。

.

linux text
1个回答
0
投票
# search for a word the long way
function find_text_the_long_way() {
    # upper case of the search term
    local upper_case_word="${1^^}"
    # one line read from the file
    local original_line=
    # same one line from file converted to upper case
    local upper_case_line=

    # read each line from standard input stream 
    while read original_line
    do
        # convert current line to upper case
        upper_case_line="${original_line^^}"

        # echo if the current line contains the search term 
        [[ "${upper_case_line//$upper_case_word/}" != "$upper_case_line" ]] && \
            echo "$original_line"
    done
}

find_text_the_long_way "alex" <"stack.txt"
© www.soinside.com 2019 - 2024. All rights reserved.