如何删除sed中带有变量的行? [英] How to to delete a line given with a variable in sed?

查看:561
本文介绍了如何删除sed中带有变量的行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用sed从名称存储在变量中的文件中删除从用户输入读取的行.现在,所有sed所做的只是打印行而已.

I am attempting to use sed to delete a line, read from user input, from a file whose name is stored in a variable. Right now all sed does is print the line and nothing else.

这是我正在使用的命令的代码段:

This is a code snippet of the command I am using:

FILE="/home/devosion/scripts/files/todo.db"
read DELETELINE
sed -e "$DELETELINE"'d' "$FILE"

这里有什么我想念的吗?

Is there something I am missing here?

编辑:用-i退出-e选项解决了我的麻烦!

Switching out the -e option with -i fixed my woes!

推荐答案

您需要界定搜索范围.

#!/bin/bash

read -r Line

sed "/$Line/d" file

将删除任何包含输入内容的行.

Will delete any line containing the typed input.

请记住,尽管sed在正则表达式上匹配,但任何特殊字符都会被视为是这样.
例如,搜索1*实际上将删除包含任意数量的1(而不是实际的1和星号)的行.

Bear in mind that sed matches on regex though and any special characters will be seen as such.
For example searching for 1* will actually delete lines containing any number of 1's not an actual 1 and a star.

还请记住,当变量扩展时,它不能包含定界符,否则命令将中断或具有未扩展的结果.

Also bear in mind that when the variable expands, it cannot contain the delimiters or the command will break or have unexpexted results.

例如,如果"$ Line"包含"/hello",则sed命令将失败并显示 sed: -e expression #1, char 4: extra characters after command.

For example if "$Line" contained "/hello" then the sed command will fail with sed: -e expression #1, char 4: extra characters after command.

在这种情况下,您可以转义/或使用其他定界符.

You can either escape the / in this case or use different delimiters.

我个人会为此使用awk

Personally i would use awk for this

awk -vLine="$Line" '!index($0,Line)' file

搜索精确的字符串,并且没有sed命令的缺点.

Which searches for an exact string and has none of the drawbacks of the sed command.

这篇关于如何删除sed中带有变量的行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆