如何在除前两行之外的文件中的所有行中grep匹配模式

时间:2018-04-27 11:14:35

标签: bash shell

我有一个名为contacts.txt的文本文件,其中填充了少量行。在这个文件中,前两行是标题,所以我不想在这两行中做任何事情。

我想从用户那里获得输入,搜索联系人文件,并显示匹配的行。如果使用tail管道传输到grep,我会获得准确的数据,但没有标题。我怎样才能获得标题行?

echo -n "Enter the value to search: ";read search1; echo -e "\n"
if [ $(tail -n +3  /root/scripts/contacts.txt | grep -i  $search1 | wc -l) -eq 0 ]; then
        echo -e "No matching rows found!!!! \n"
        echo -n "To re-enter press r. To go back to main menu press any key: "; 
        read reenter;
        echo -e "\n";
        if [ "$reenter" == "R" ] || [ "$reenter" == "r" ]; then
           remove_entry  # calling a function
        else
           inputscan # calling a function
        fi
else
        echo -n "Number of Matching rows found:"; tail -n +3  /root/scripts/contacts.txt | grep -i $search1 | wc -l; echo -e "\n";
        tail -n +3 /root/scripts/contacts.txt | grep -i "$search1" | column -t -s";";
fi

3 个答案:

答案 0 :(得分:1)

正如你所说的前两行是标题所以修改你的脚本如下所示打印标题: -

echo -n "Number of Matching rows found:"; tail -n +3  /root/scripts/contacts.txt | grep -i $search1 | wc -l; echo -e "\n";

#Print first two lines of the file
head -2 /root/scripts/contacts.txt 

tail -n +3 /root/scripts/contacts.txt | grep -i "$search1" | column -t -s";";

答案 1 :(得分:0)

早上好,我对你的剧本做了一些修改:

  • 将contacts.txt文件路径放在一个变量中,以避免不得不反复输入(如果以后更改它会很好!)
  • 将用于计算变量匹配数的代码放入,以避免运行该代码两次
  • 添加head -2以输出标题行。

    #!/bin/bash
    
    echo -n "Enter the value to search: ";read search1; echo -e "\n"
    
    contactsfile='/root/scripts/contacts.txt'
    number_matching_rows=$(tail -n +3 $contactsfile | grep -i  $search1 | wc -l)
    
    if [ $number_matching_rows -eq 0 ]; then
            echo -e "No matching rows found!!!! \n"
            echo -n "To re-enter press r. To go back to main menu press any key: "; 
            read reenter;
            echo -e "\n";
            if [ "$reenter" == "R" ] || [ "$reenter" == "r" ]; then
               remove_entry  # calling a function
            else
               inputscan # calling a function
            fi
    else
            echo "Number of Matching rows found: $number_matching_rows"
            head -2 $contactsfile
            tail -n +3 $contactsfile | grep -i "$search1" | column -t -s";";
    fi
    

答案 2 :(得分:0)

您可以使用<p id="demo"></p>并通过在大括号块中组合它们来管道多个命令的输出。

head -2
相关问题