【问题标题】:how to delete a line from a text file in shell programming [duplicate]如何在shell编程中从文本文件中删除一行[重复]
【发布时间】:2015-01-23 06:43:33
【问题描述】:

您好,我正在尝试创建一个程序,该程序将读取用户输入的书名及其作者。它将搜索记录在文本文件中的记录并删除包含用户输入的输入的行。我尝试使用 sed 但我一直显示此错误“sed: -e expression #1, char 3:命令后的多余字符”以下是我的代码。

echo "Title: "
read title
echo "Author: "
read author

if !( grep -i -q -e "$title" "BookDB.txt" | 
grep -i -q -e "$author" "BookDB.txt" ) ; then   

echo "Error! Book does not exist!"

else 
details="$title:$author"
echo $details
sed -i '/$details/d' "BookDB.txt"

fi

提前感谢您!对不起,如果这个问题对你来说是菜鸟,如果这个问题与之前提出的任何问题相似,我很抱歉,因为我真的找不到适用于我的情况的代码。

【问题讨论】:

  • 使用双引号:sed -i "/$details/d" "BookDB.txt"
  • 即使我使用双引号,文本文件中的行也不会被删除。
  • 我对一个示例文件进行了测试,它对我有用。确保数据格式正确。
  • sed 对此并不好,正如我之前用an eerily similar problem 告诉某人的那样,因为书名可以包含特殊字符(我怀疑这正是您遇到的问题)。链接后面的答案应该对您有所帮助,您只需将$title$author 之间的空格替换为:

标签: bash shell variables sed title


【解决方案1】:

你必须这样使用,

 sed -i '/'$details'/d' "BookDB.txt"

我希望它会起作用。在sed 之前,您必须验证您需要的详细信息是否已放入您正在使用的变量中。

【讨论】:

    【解决方案2】:

    您在 sed 正则表达式中使用单引号而不是双引号。 您的字符串 $details 无法扩展,因此,sed literraly 读取 '$details' 而不是 "$details" 的内容

    #!/bin/sh
    
    errorExit() {
        case $1 in
            1) msg="book db file not found";;
            2) msg="Book does not exist!";;
            *) ;;
        esac    
        echo "==> error : $msg"
        exit $1
    }
    
    showdb() {
    # Show content of the db
        echo "==> Content of $bookdb >"
        cat $bookdb
        echo "<"
    }
    
    bookdb="BookDB.txt"
    
    # Create DB
    echo "Ubik:Dick" > $bookdb
    echo "Apes Planet:Boule" >> $bookdb
    
    # Test db file exists
    [ -f $bookdb ] || errorExit 1
    
    # Show content of the db
    showdb
    
    # Read the choice
    echo -n "Title: "
    read title
    echo -n "Author: "
    read author
    
    # Find and delete data
    details="$title:$author"
    if !( grep -i -q -e "$details" $bookdb ) ; then   
        errorExit 2
    else 
        echo "==> details : $details"
        sed -i -e "/$details/d" $bookdb 
    fi
    
    # Show content of the db
    showdb
    
    exit 0
    

    输出:

    $ ./test 
    ==> Content of BookDB.txt >
    Ubik:Dick
    Apes Planet:Boule
    <
    Title: Ubik
    Author: Dick
    ==> details : Ubik:Dick
    ==> Content of BookDB.txt >
    Apes Planet:Boule
    <
    

    【讨论】:

      猜你喜欢
      • 2010-11-17
      • 1970-01-01
      • 2018-01-31
      • 2015-09-09
      • 2023-03-23
      • 1970-01-01
      • 2017-03-12
      • 1970-01-01
      相关资源
      最近更新 更多