简体   繁体   English

有没有办法在linux的conf文件中将文本添加到字符串的末尾?

[英]Is there a way to add text to the end of a string in a conf file in linux?

I have a problem: I have a file that, if I knew how, I would like to edit from the command.我有一个问题:我有一个文件,如果我知道如何,我想从命令中进行编辑。 I would like to locate the file by content on that line.我想通过该行的内容定位文件。

I am in CyberPatriot, and my team is second in my state.我在 Cyber​​Patriot,我的团队在我所在的州排名第二。 I know someone who is on the number one team and I know one of the people on the first team.我认识一个在第一队的人,我认识一个在第一队的人。 It kills me so I want to make a list of commands that I can go off of to make it faster and more efficient.它杀死了我,所以我想列出一个我可以执行的命令列表,以使其更快、更高效。

Imagine I had this file:想象一下我有这个文件:

example
oof
goo
random
yes

and I wanted to change it to this:我想把它改成这样:

example
oof
goo
random 'added text'
yes

How do I do so?我该怎么做? I know I can use the echo command to add text to the end of a file, but I don't know how to add text to the end of a specific line.我知道我可以使用echo命令将文本添加到文件的末尾,但我不知道如何将文本添加到特定行的末尾。

Thanks, Owen谢谢,欧文

You can use sed for this purpose.为此,您可以使用 sed。

sed 's/random/& Hello World/' file

to append text to the matched string.将文本附加到匹配的字符串。

You can use ^random$ to make sure the entire line is matched, before appending.在追加之前,您可以使用^random$来确保整行匹配。

If you need to modify the file directly, you can use the -i flag, which facilitates in-place editing.如果需要直接修改文件,可以使用-i标志,方便就地编辑。 Further, using -i.bak creates a backup of the original file first before modifying it, as in此外,使用-i.bak在修改它之前首先创建原始文件的备份,如

sed -i.bak 's/random/& Hello World/' file

The original copy of the file can be found in file.bak文件的原始副本可以在file.bak找到

More about sed : https://www.gnu.org/software/sed/manual/sed.html有关sed更多信息: https : //www.gnu.org/software/sed/manual/sed.html

Use something like below使用类似下面的东西

sed '4!d' file | xargs -I{} sed -i "4s/{}/{} \'added text\'/" file

Basically in the above command, we are getting the 4th line of the file using sed sed '4!d' file and then using this line to replace it with the same text and some new text( added text )基本上在上面的命令中,我们使用 sed sed '4!d' file获取文件的第 4 行,然后使用此行将其替换为相同的文本和一些新文本( added text

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM