[英]fIm trying to find a string betwen two match patterns and then add that string before a pattern using sed
[英]To add a string before and after, if the specific string is matched between patterns using sed in bash
问题:在bash中使用sed的模式之间是否匹配指定的字符串前后添加一个字符串?
在下面的代码中,我想在object Host "kali" {上方添加 /* 一行,并将 */ 添加到}出现后的下一行(而不是最后一次出现 } )。
这是我的代码
object Host "linux" {
import "windows"
address = "linux"
groups = ["linux"]
}
object Host "kali" {
import "linux"
address = "linux"
groups = [linux ]
}
object Host "windows" {
import "linux"
address = "linux"
groups = ["windows" ]
}
这是预期的 output:
object Host "linux" {
import "windows"
address = "linux"
groups = ["linux"]
}
/*
object Host "kali" {
import "linux"
address = "linux"
groups = [linux ]
}
*/
object Host "windows" {
import "linux"
address = "linux"
groups = ["windows" ]
}
**This is what I tried**
#! /bin/bash
NONE='\033[00m'
RED='\033[01;31m'
GREEN='\033[0;32m'
clear
echo -e "Enter the names to comment in config file"
cat > comment-file.txt
clear
echo -e "#################################################################################"
echo "Please wait. The names will be commented shortly............"
echo -e "#################################################################################"
echo "Dont press any button, Please hold on...."
while read -r names
do
loc=$(grep -il "object.*Host.*\"$names.*\"" /home/jo/folders/test-sc/*.txt)
if [ -z $loc ]
then
echo -e " $names$RED No Object definition found $NONE "
else
sed -i '/object Host \"$names.*\" {/ { s,^,/*\n,
: loop
/}/ {
s,$,\n*/,
p
d
}
N
b loop
}' "$loc"
echo -e " $names - $loc - $GREEN Object host defenition commented $NONE "
fi
done < comment-file.txt
echo -e "#################################################################################"
echo -e "\t\t\t\t Script completed \t\t\t\t"
echo -e "#################################################################################"
rm -rf comment-file.txt
错误:
output 文件中没有进行任何更改,这意味着 /home/jo/folders/test-sc/*.txt
这可能对您有用(GNU sed):
sed -e '/object Host "kali"/{i\/*' -e ':a;n;/}/!ba;a\*/' -e '}' file
查找包含object Host "kali"
在它之前插入一行包含/*
,读取/打印更多行直到包含}
和 append 行*/
。
找到object Host "kali" {
后:
/*\n
}
, d
p
\n*/
到模式空间,打印并删除N
下一行到模式空间并循环回到步骤 2。sed -e '/object Host "kali" {/ {
s,^,/*\n,
: loop
/}/ {
s,$,\n*/,
p
d
}
N
b loop
}'
.... 附录...要正确传递“$names”成为 sed 脚本的一部分,我们需要遵循sh
的引用规则...这个想法是将“$names”嵌入到 sed脚本,并且 sed 行将如下所示:
sed -i -e "/object Host \"$names\" {/ {
s,^,/*\n,
: loop
/}/ {
s,$,\n*/,
p
d
}
N
b loop
}" "$loc"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.