繁体   English   中英

awk -F最终删除我想要返回的字段

[英]awk -F ends up deleting the field I'm trying to return

所以我有一个我必须为课程编写的库脚本。 它有几个功能,如addbook,deletebook,checkout等。问题出在我的结账功能。

colin @Colin-Samsung:〜$ bash --version GNU bash,版本4.2.45(1)-release(x86_64-pc-linux-gnu)版权所有(C)2011 Free Software Foundation,Inc。许可证GPLv3 +:GNU GPL版本3或更高版本http://gnu.org/licenses/gpl.html

所以首先是我的字符串(以逗号分隔的字段)

表格书,作者,图书馆,日期

string= Unix for programmers,Graham Glass,mylibrary,11-11-13

我已经在代码的前几行中声明了我的标题,库和日期,但是当我尝试声明作者时我使用了这行代码

author=`awk -F, '/'$title'/ {print $2}' $library`

我相信这就是我的问题所在

最终发生在字符串上的是作者变为null所以在我的函数完成之后,现在是字符串

 Unix for programmers,,mylibrary,11-11-13

所以看起来行中出现了一些事情:'/'$ title'/ {print $ 2}'我的问题是什么?

我试过了

author=`awk -F, "/'$title'/ {print $2}" $library`

我也试过##

author=`egrep "$title" $library | awk -F, '{print $2}' $library`

但是在这两个帐户上,我都会收到一些错误,无论是失控的正则表达式还是无效的命令。

这是我正在尝试解决的整个功能

checkout(){

echo please enter your username 
read username
uCount=`egrep "$username" $library | wc -l`
if (( $uCount >=3 ))
then 
    echo "Sorry, you can only have 3 books checked out at a time"
else 
    echo "what is the name of the book you would like to check out?"
    read title
    exists=`egrep "$title" $library | wc -l`
    if (( $exists == 0 ))
    then 
        echo "Sorry, but this book does not exist"
    else 

    author=`awk -F, '/'$title'/ {print $2}' $library`

    ##author=`egrep "$title" $library | awk -F, '{print $2}' $library`
    ##author=`awk -F, "/'$title'/ {print $2}" $library`
    ##String = unix,graham glass,mylib,11-11-13

    updated=$title,$author,$username,`date +%F`
    sed -e "/$title/d" $library > $tmp
    echo $updated >> $tmp
    mv $tmp $library
    echo "$title succesfully checked out"
    fi
fi

请指教。 在此先感谢您的帮助

要将变量添加到awk,请执行此操作。

awk -v var="$variable" '{$0=var}' file

要么

awk '{$0=var}' var="$variable" file

所以这:

author=`awk -F, '/'$title'/ {print $2}' $library`

应该是这样的

author=$(awk -F, '$0~var {print $2}' var="$title" $library)

PS最好使用括号var=$(code)比较回tics

脚本中有很多shell错误,它可能在很多方面对各种输入和数据值失败。 你也有逻辑问题。 想象一下如果一个名叫Theo想要使用你的图书馆并且你的图书馆里有3本书的标题包含了Theory这个词会怎么样? 可怜的老西奥永远无法借书!

shell是一个可以从中调用工具的环境。 它具有编程结构,可帮助您对工具的调用进行排序。 就这些。 您不应该尝试使用shell构造来解析文本文件 - 这就是awk发明要做的事情,所以它非常擅长。

如果你想帮助写这个,请告诉我们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM