问题:要在前后添加一个字符串,如果指定的字符串在 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" ]
}
这是预期的输出:
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
错误:
输出文件中未进行任何更改,这意味着/home/jo/folders/test-sc/*.txt
最佳答案
这可能对你有用(GNU sed):
sed -e '/object Host "kali"/{i\/*' -e ':a;n;/}/!ba;a\*/' -e '}' file
查找包含 object Host "kali"
的行,在包含 /*
的行之前插入一行,读取/打印更多行,直到包含 }
的行,并附加行 */
。
关于linux - 如果特定字符串在 bash 中使用 sed 在模式之间匹配,则在前后添加字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58896916/