2017-07-06 66 views
0

我有简单的文件:如何编写bash脚本,该脚本从开始从开始直到特定符号的文件返回行?

line1(sometext) 
line222(other_text) 
line333(other text) 

我传递给脚本符号之前字的参数的一部分“(” 我怎样才能再检查一下使用grep命令,如果这行存在 比如我通过在参数字line222? - 它返回line222(other_text)

,但我通过“2号线” - 它说,该行未找到 现在我有这样的代码,这给了错误的结果,如果我键入一个符号

if ! grep home "myfile.txt" | grep -- "$1"; then 
    echo "Line doesn't exist" 
fi 
+0

您需要包含您的代码;-)。请阅读http://stackoverflow.com/help/how-to-ask,http://stackoverflow.com/help/dont-ask,http://stackoverflow.com/help/mcve并参加[tour]( http://stackoverflow.com/tour)在发布更多Q​​之前。祝你好运。 – shellter

+0

你需要什么'grep home'部分? 'home'似乎不会出现在您的文件中。 –

回答

0

可以验证某一行是否存在在你的文件,如下所示不存在:

if [[ $(grep "^${1}" "myfile.txt") ]]; then 
    echo "Line starts with \"${1}\" exists" 
else 
    echo "Line starts with \"${1}\" doesn't exist" 
fi 

,或者如果你只是想打印时它不存在的输出信息,那么这可能帮助:

if [[ ! $(grep "^${1}" "myfile.txt") ]]; then 
    echo "Line starts with \"${1}\" doesn't exist" 
fi 

grep "^${1}"搜索文本模式,^${1}意味着,你传递给你的脚本starting with the variable[[ ... ]]测试条件(bash方式)和!符号否定测试条件。