gpt4 book ai didi

linux - 使用变量写入文件而不重复

转载 作者:太空宇宙 更新时间:2023-11-04 03:46:32 25 4
gpt4 key购买 nike

尝试在 shell 中编写一个函数,该函数采用三个参数 a_text_to_be_matchednew_textfile_name。如果找到 text_to_be_matched,则整行将被 new_text 替换,否则它只是回显文件中的 new_text。以下是我尝试过的代码,但当 $to_write 之间有空格时它会中断。

function write_once(){
to_grep="$1";
to_write="$2";
file="$3";
grep $to_grep $file;
if [ $? -eq 0 ]; then
sed -i '/'"$to_grep"'/c\'$"to_write" $file;
else
echo "$to_write" >> "$file";
fi
}

最佳答案

尝试如下:

sed -i "s/(.*)?(${text_to_be_matched})?(.*)?/${new_text}" $file 

关于linux - 使用变量写入文件而不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28012892/

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