Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.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_Shell_Sed - Fatal编程技术网

Bash 如何使用变量指定要用sed替换的行

Bash 如何使用变量指定要用sed替换的行,bash,shell,sed,Bash,Shell,Sed,我想根据变量替换文本文件中的特定行。所以如果我的变量正好是4,我就不能写: sed -i '4 creplacememt' text.txt 我想知道如何做这样的事情: num=4 str="$num creplacement" sed -i $str text.txt 这给了我一个错误。我到底做错了什么/我怎样才能做到这一点 #!/bin/bash -e # Replace given the line number with the given string in

我想根据变量替换文本文件中的特定行。所以如果我的变量正好是4,我就不能写:

sed -i '4 creplacememt' text.txt
我想知道如何做这样的事情:

num=4
str="$num creplacement" 
sed -i $str text.txt
这给了我一个错误。我到底做错了什么/我怎样才能做到这一点

#!/bin/bash -e

# Replace given the line number with the given string in the given file

line=$1
str=$2
shift 2

sed -i "$line{s/.*/$str/}" "$@"
用法:

script [line-number] [string] [file]

# Eg:
script 4 foobar my-file
script 3,9 'lines three to nine of "my-file" now contain this very string' my-file
您必须在替换字符串中转义斜杠


您还可以使用正则表达式(
/regex.*/
)代替行号。

引号
sed-i-e“$str”text.txt
双引号可以为您节省一些麻烦。如果变量可以包含sed特殊字符,则这些字符是不够的。请设置。sed-i-e“$str”text.txt