在 sed -i (regex?) bash 中使用变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19252880/
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 08:13:35  来源:igfitidea点击:

Using variable inside of sed -i (regex?) bash

bashvariablessed

提问by Joel Damata

I've looked at the other sedpages here and i cannot find one that uses -iwith a variable in the regex search portion. I am trying to cut out a requested line in the file myresolv.confand by getting its line number. 5 people in my class are all stuck :( Any help is awesome

我查看了sed此处的其他页面-i,但在正则表达式搜索部分找不到与变量一起使用的页面。我试图在文件中删除请求的行myresolv.conf并获取其行号。我班上的 5 个人都被卡住了 :( 任何帮助都很棒

line=$(grep -n "" ./myresolv.conf | cut -d: -f1)

sed -i "$line"  ./myresolv.conf

回答by jkshah

I assume, you mean remove linewhen you say cut out line.

我想,你的意思是remove line当你说cut out line.

Try using grepwith -voption. I believe you don't need sedhere.

尝试使用grepwith-v选项。我相信你不需要sed这里。

grep -v "" ./myresolv.conf

Or if you want to delete line in the file itself

或者,如果您想删除文件本身中的行

sed -i.bak "//d" ./myresolv.conf

It's good to use -iwith .bakto create backup file before overwirting changes.

在覆盖更改之前使用-iwith.bak创建备份文件很好。

回答by twalberg

It would seem you want to delete a specific line from a file. You're hopefully getting a single line number in your linevariable (but beware - if you have multiple lines that match, you're going to get a list of numbers, and that will cause the rest of your process to explode). The problem you have is that the command you are feeding sedis simply the line number - you are not specifying anything for sedto do with that line number. So, perhaps you want this:

您似乎想从文件中删除特定行。您希望在您的line变量中获得一个单一的行号(但要注意 - 如果您有多个匹配的行,您将获得一个数字列表,这将导致您的其余过程爆炸)。您遇到的问题是您提供的命令sed只是行号 - 您没有指定sed与该行号有关的任何内容。所以,也许你想要这个:

sed -i "${line}d" file.txt

If I've misunderstood your question, and you're not wanting to delete that line, but simply print it, then replace the dwith p...

如果我误解了你的问题,而你不想删除该线,但只是打印出来,然后更换dp...