Shell脚本来打印包含用户添加的单词的行

时间:2018-11-15 14:07:13

标签: bash shell awk grep

我有一个名为data.txt的文件,其中包含以下内容:

1440;150;1000000;pizza;hamburger
1000;180;56124;coke;sprite;water;juice
566;40;10000;cake;pizza;coke 

我想制作一个程序,要求用户输入,然后打印出包含给定单词的行。

例如:

如果我输入可乐,它应该打印出第二行和第三行。如果输入hambuger,则只应打印第一行。

这是我尝试的代码,但是它不起作用。有人可以帮我吗?

echo "Enter a word"`
read word 

while read line; do
numbersinthefile=$(echo $line | cut -d';' -f4);
if [ $numbersinthefile -eq $num ]; then
echo $line;
fi
done

我早先忘了提到我希望程序允许用户进行多次输入。示例:

如果我输入“ pizza sprite”,它会显示第一行和第二行。

3 个答案:

答案 0 :(得分:3)

那是一个简单的grep,不是吗?

read -p "Enter a word: " word
grep -F "$word" file

添加-w以使coke仅与coke匹配,而不与cook匹配。

read -p "Enter a word: " word
grep -Fw "$word" file

答案 1 :(得分:2)

请您尝试一次。

cat script.ksh
echo "Please enter word which you want to look for in Input_file:"
read value

awk -v val="$value" '$0 ~ val'  Input_file

运行上面的代码后,下面是它的工作原理。

./script.ksh
Please enter word which you want to look for in Input_file:
coke
1000;180;56124;coke;sprite;water;juice
566;40;10000;cake;pizza;coke


EDIT: :如果要将多个值传递给脚本,那么如何将它们作为参数传递给程序本身呢?

cat script.ksh
for var in "$@"
do
  awk -v val="$var" '$0 ~ val'  Input_file
done

然后以以下方式运行脚本。

script.ksh test coke cake etc

答案 2 :(得分:1)

以下是awk中的一个,它接受部分匹配:

'BlockDeviceMappings': [{'DeviceName': '/dev/sda1',
                                                       'Ebs': {'AttachTime': datetime.datetime(2018, 7, 14, 16, 44, 31, tzinfo=tzutc()),
                                                               'DeleteOnTermination': True,
                                                               'Status': 'attached',
                                                               'VolumeId': 'vol-096cd0ee0ace156df'}},

输出

$ awk '
BEGIN {
    FS=";"                    # file field sep
    printf "Feed me text: "   # text for prompt
    if((getline s < "-")<=0)  # read user input
        exit                  # exit if unsuccessful
}
{
    for(i=4;i<=NF;i++)        # iterate fields from file records >= 4
        if($i~s) {            # if match (~ since there was a space in eof NR==3) 
            print
            next              # only output each matching record once
        }
}' file
相关问题