简体   繁体   English

当行包含变量时,如何用单个命令替换文件中的一行文本?

[英]How can I replace a line of text in a file with a single command when the line contains a variable?

I have a script called script.sh which has the contents我有一个名为script.sh的脚本,其中包含内容

export HELLO=$WORLD

I want to change it using a single command to我想使用单个命令将其更改为

export HELLO=${WORLD:2:3}

I'm attempting to use the sed command but i'm new to linux and can't quite get it right.我正在尝试使用 sed 命令,但我是 linux 的新手,不能完全正确。 Here's what I have这就是我所拥有的

sed -i 's/export HELLO=$WORLD/export HELLO=${WORLD:2:3}' script.sh

How should this line be written to replace the text correctly?应该如何编写此行以正确替换文本?

You just missed a / at the very end:你只是在最后错过了一个/

sed -i 's/export HELLO=$WORLD/export HELLO=${WORLD:2:3}/' script.sh
                                                       ^
                                       this / is missing

The $ is a special symbol that means end of line, also as @yvesonline points out you are missing the trailing /. $ 是一个特殊符号,表示行尾,正如@yvesonline 指出的那样,您缺少尾随 /。 This is how I would do it:我会这样做:

sed -i 's/\(export HELLO=\$\)\(WORLD\)/\1{\2:2:3}/' script.sh

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在文本文件中逐行替换特定行? - How can I replace a specific line by line number in a text file? 如何在Linux中从命令行替换文件中的此文本? - How do I replace this text in a file from the command line in Linux? 我如何使用sed -i命令替换从文件中特定行开始到另一行的字符出现? - How can i use sed -i command to replace the occurance of character starting from particular line in a file till another line? 如何在 bash 命令行或脚本中位置更改的文件中替换特定字符? - How can I replace a specific character in a file where it's position changes in bash command line or script? 如何使用sed在命令行中提取单个值? - How can I use sed to extract a single value in command line? 如何用 shell 脚本替换文本文件中的特定行? - How can replace a specific line in a text file with a shell script? 如何通过匹配上一行将sed替换为文本 - How can i replace text with sed by matching previous line 如何将命令 output 存储在一个变量中而不是一行? - How can I store command output in a variable not on just one line? 如何使用linux命令行工具列出文本文件中使用的唯一字符? - How can I list unique characters used in a text file using linux command line tools? 如何使用PHP缩进文本输出到命令行? - How can I indent text output to the command line with PHP?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM