从文件中读取此代码

时间:2017-11-19 13:27:11

标签: linux bash

你好我们在linux shell脚本中编写代码,但代码只能从键盘读取我想改变它来读取文件,例如如果我写./car.sh lamborghini.txt它应该给我最昂贵的模型

代码是这样的:

#!/bin/sh
echo "Choose one of them"
read manu
sort -t';' -nrk3 auto.dat > auto1.dat
grep $manu auto1.dat | head -n1 | cut -d';' -f2

和auto.dat文件包含以下内容:

Lamborghini;Aventador;700000
Lamborghini;Urus;200000
Tesla;ModelS;180000
Tesla;ModelX;140000
Ford;Mustang;300000
Ford;Focus;20000

2 个答案:

答案 0 :(得分:0)

read命令始终从stdin读取。您可以使用重定向 <来读取文件的内容。

从文件的内容中读取$manu

#!/bin/sh
read manu < "$1"
sort -t';' -nrk3 auto.dat | grep "$manu" | head -n1 | cut -d';' -f2

此版本的脚本需要文件名作为命令行参数。所述文件的第一行将存储在$manu中。例如:

./car.sh fileWithSelection.txt

该文件应包含您在旧脚本中输入的文本。

从命令行参数

中读取$manu

在我看来,直接解释命令行参数更有意义,而不是使用文件并将它们传递给脚本。

#!/bin/sh
manu="$1"
sort -t';' -nrk3 auto.dat | grep "$manu" | head -n1 | cut -d';' -f2

示例:

./car.sh "text you would have entered in your old script."

答案 1 :(得分:0)

您可以尝试这种方式,但文件Tesla.txt必须包含特斯拉

[tag_constants.TRAINING]
相关问题