gpt4 book ai didi

如果其他字符串出现在 'n' 行之前,linux 替换字符串

转载 作者:太空宇宙 更新时间:2023-11-04 10:36:35 24 4
gpt4 key购买 nike

我有一个简单的问题。

在具有下一个结构的文件中。

condition line1
line2
line3
String to change depending on the condition.

此结构在文件中重复了未定义的次数。
我必须根据第一行的值更改第四行。在文件的所有出现中。我在 shell 脚本中创建了下一个函数,并且工作正常。

function normalizer() {
list=$(grep -n "STRING" $1 |cut -f1 -d:|wc -l)
coso=1
while [ $coso -le $list ];
do
direc=$(grep -n "STRING" $1 |cut -f1 -d:|head -$coso|tail -1)
str=$(perl -wne "print if $. == ($direc - 6)" $1)
if [ "$str" == "STING 2" ]; then
sed -i "${direc}s/STRING/DORSOC CARATR/" $1
else if [ "$str" == "STRING 3" ]; then
sed -i "${direc}s/STRING/DORSOC CARATU/" $1
else
echo dont match
fi
fi
let coso=$coso+1
done
}

但效率不高,因为每次更改时 sed 都会复制文件。那么,您将如何做才能使其更有效率?

编辑:为了澄清,第 4 行不能来,然后我必须验证它存在,然后验证条件之前的 3 行。

最佳答案

给出这个输入文件:

condition1 line1
line2
line3
String to change depending on the condition.
condition2 line1
line2
line3
String to change depending on the condition.
condition1 line1
line2
line3
String to change depending on the condition.

你可以使用这个 sed 脚本 (sed -f script.sed 输入):

/condition1/,+3 {t; t; s/change/XXXXX/ }
/condition2/,+3 {t; t; s/change/YYYYY/ }

这会产生以下输出:

condition1 line1
line2
line3
String to XXXXX depending on the condition.
condition2 line1
line2
line3
String to YYYYY depending on the condition.
condition1 line1
line2
line3
String to XXXXX depending on the condition.

(+3 范围地址是 GNU 扩展,因此您必须使用 GNU sed)

关于如果其他字符串出现在 'n' 行之前,linux 替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37165703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com