Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在bash中如何替换字符串变量,并将其设置为sed命令_Bash_Sed - Fatal编程技术网

在bash中如何替换字符串变量,并将其设置为sed命令

在bash中如何替换字符串变量,并将其设置为sed命令,bash,sed,Bash,Sed,在bash脚本文件中,我设置了如下一个变量: current_path=`pwd` sed -i "1s/.*/working_path='$current_path';/" file1.sh 我想运行这个脚本,将file1.sh的第一行替换为working_path='$current_path',但是当前路径具有/,并且在sed命令中,/在sed替换模式中预定义。 我试过这样做: current_path1="${current_path/\//\\\/}" 在上

在bash脚本文件中,我设置了如下一个变量:

    current_path=`pwd`
    sed -i "1s/.*/working_path='$current_path';/" file1.sh
我想运行这个脚本,将
file1.sh
的第一行替换为
working_path='$current_path'
,但是
当前路径
具有
/
,并且在
sed
命令中,
/
sed
替换模式中预定义。 我试过这样做:

    current_path1="${current_path/\//\\\/}"
在上面的一行中,我想将变量
当前路径
中的
/
替换为
\/
,然后将
当前路径1
输入到
sed
命令中,但也有一个错误

你能给我一些建议吗?谢谢。

试试这个

sed -i -e "1s@.*@working_path='$current_path';@" file1.sh

在替换命令中使用
@
而不是
/

您可以为
s///
命令使用不同的分隔符:

current_path=`pwd`
sed -i "1s|.*|working_path='$current_path';|" file1.sh
但您并不是在此处进行搜索和替换,而是要插入新行并删除旧行:

current_path=`pwd`
sed -i -e "1i\working_path='$current_path)';" -e 1d file1.sh

您真的要更改
.sh
文件的第一行吗?您要删除she-bang行吗?

请在模式字符串的开头添加“/”。它用字符串替换模式的所有匹配项

 current_path1="${current_path//\//\\\/}"

是的,先生,当我在终端中运行这个
sed-I“1s/*/working\u path='\/home\/user\/Desktop'/“file1.sh
时,它工作了,但它会将
\/bin/bash
替换为
working\u path='/home/user/Desktop;'我的搜索和替换失败,知道原因吗
sed-i“s”`“$foo”`“$bar”/g“$file”
。错误是:
命令替换:第28行:语法错误:文件意外结束;sed:-e expression#1,char 22:unterminated's'命令
应该在那里吗?谢谢,先生,拉法的答案,第一个答案有效。可能是@tripleee的重复,谢谢。那篇文章很有帮助。也许我当时找不到那篇文章,我面临着这个问题。或者我使用了不同的关键词,这样搜索引擎就不会返回那篇文章的索引。因此,我在这里发了一个新帖子。