bash 如何删除sed中给定变量的行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35157623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:11:00  来源:igfitidea点击:

How to to delete a line given with a variable in sed?

linuxbashsed

提问by barefly

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

我试图用来sed从名称存储在变量中的文件中删除一行,从用户输入中读取。现在sed所做的只是打印行,没有别的。

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?

有什么我在这里想念的吗?

Edit:Switching out the -eoption with -ifixed my woes!

编辑:切换-e选项-i解决了我的问题!

回答by 123

You need to delimit the search.

您需要对搜索进行定界。

#!/bin/bash

read -r Line

sed "/$Line/d" file

Will delete any line containing the typed input.

将删除包含键入的输入的任何行。

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.

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

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

还要记住,当变量扩展时,它不能包含分隔符,否则命令会中断或产生未扩展的结果。

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

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

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

/在这种情况下,您可以转义或使用不同的分隔符。

Personally i would use awk for this

我个人会为此使用 awk

awk -vLine="$Line" '!index(
read -p "Enter a regex to remove lines: " filter
grep -v "$filter" "$file"
,Line)' file

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

它搜索确切的字符串并且没有 sed 命令的缺点。

回答by glenn Hymanman

You might have success with grep instead of sed

您可能会成功使用 grep 而不是 sed

tmp=$(mktemp)
grep -v "$filter" "$file" > "$tmp" && mv "$tmp" "$file"

Storing in-place is a little more work:

就地存储需要更多的工作:

grep -v "$filter" "$file" | sponge "$file"

or, with sponge

或者,与 sponge

##代码##

Note: try to get out of the habit of using ALLCAPSVARS: one day you'll accidentally use PATH=...and then wonder why your script is broken.

注意:尽量改掉使用 ALLCAPSVARS 的习惯:有一天你会不小心使用PATH=...然后想知道为什么你的脚本被破坏了