[英]remove lines that contain exact string in bash script with sed
I'm trying to run a bash script that removes lines from a file with only the specific string I pass to it, " /home/ken/sed.txt ".我正在尝试运行一个 bash 脚本,该脚本从文件中删除行,其中仅包含我传递给它的特定字符串“ /home/ken/sed.txt ”。
Current script which does nothing:当前什么都不做的脚本:
#!/bin/bash
script="\\/home\\/ken\\/sed.txt"
sed -i "/\<$script\>/d" /home/ken/sed.txt
This deletes all rows:这将删除所有行:
#!/bin/bash
script="\\/home\\/ken\\/sed.txt"
sed -i "/$script/d" /home/ken/sed.txt
The file:文件:
1 1 1 1 1 /home/ken/sed.txt
6 6 6 6 6 /home/ken/sed.txt
2 2 2 2 2 /home/ken/sed.txt
6 6 6 6 6 /home/ken/sed.txt
3 3 3 3 3 /home/ken/sed.txt
3 3 3 3 3 /home/ken/sed.txt
5 5 5 5 5 /home/ken/sed.txt
1 1 1 1 1 a/home/ken/sed.txt
6 6 6 6 6 a/home/ken/sed.txt
2 2 2 2 2 a/home/ken/sed.txt
6 6 6 6 6 a/home/ken/sed.txt
3 3 3 3 3 a/home/ken/sed.txt
3 3 3 3 3 a/home/ken/sed.txt
5 5 5 5 5 a/home/ken/sed.txt
Desired outcome:期望的结果:
1 1 1 1 1 a/home/ken/sed.txt
6 6 6 6 6 a/home/ken/sed.txt
2 2 2 2 2 a/home/ken/sed.txt
6 6 6 6 6 a/home/ken/sed.txt
3 3 3 3 3 a/home/ken/sed.txt
3 3 3 3 3 a/home/ken/sed.txt
5 5 5 5 5 a/home/ken/sed.txt
Any assistance would be greatly appreciated.任何帮助将不胜感激。
script='/home/ken/sed.txt'
sed -n "\|\b$script|p" file
Output:输出:
1 1 1 1 1 a/home/ken/sed.txt 6 6 6 6 6 a/home/ken/sed.txt 2 2 2 2 2 a/home/ken/sed.txt 6 6 6 6 6 a/home/ken/sed.txt 3 3 3 3 3 a/home/ken/sed.txt 3 3 3 3 3 a/home/ken/sed.txt 5 5 5 5 5 a/home/ken/sed.txt
I switched from //
p to \\||p
to avoid escaping /
.我从//
p 切换到\\||p
以避免转义/
。
From man sed
:来自man sed
:
\\cregexpc
: Match lines matching the regular expression regexp.\\cregexpc
: 匹配与正则表达式 regexp 匹配的行。 The c may be any character. c 可以是任何字符。
As usual when wanting to edit a file in place, I recommend ed
over sed -i
:像往常一样,当想要就地编辑文件时,我推荐ed
over sed -i
:
#!/bin/sh
script=" /home/ken/sed.txt"
ed -s sed.txt <<EOF
g!$script!d
w
EOF
Note the addition of a space in your $script
variable, to avoid matching the a/home/ken/sed.txt
lines.请注意在$script
变量中添加一个空格,以避免匹配a/home/ken/sed.txt
行。 Without that, every line in your example file is deleted, as you've seen.否则,如您所见,示例文件中的每一行都将被删除。
Why is sed needed?为什么需要sed? I think you could just grep with the "--fixed-strings" and the "--invert-match" option:我认为您可以使用“--fixed-strings”和“--invert-match”选项进行grep:
$ fgrep -v ' /home/ken/sed.txt' file.txt
1 1 1 1 1 a/home/ken/sed.txt
6 6 6 6 6 a/home/ken/sed.txt
2 2 2 2 2 a/home/ken/sed.txt
6 6 6 6 6 a/home/ken/sed.txt
3 3 3 3 3 a/home/ken/sed.txt
3 3 3 3 3 a/home/ken/sed.txt
5 5 5 5 5 a/home/ken/sed.txt
grep -F -v ' /home/ken/sed.txt' file.txt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.