Bash 如何使用变量指定要用sed替换的行
我想根据变量替换文本文件中的特定行。所以如果我的变量正好是4,我就不能写: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
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