简体   繁体   English

bash:如何用部分内容替换文本文件中的整行

[英]bash: How to replace an entire line in a text file by a part of its content

I have a text file, called texto.txt in Documentos folder, with some values like the ones below:我在 Documentos 文件夹中有一个名为 texto.txt 的文本文件,其中包含一些如下所示的值:

cat ~/Documentos/texto.txt

65f8: Testado
a4a1: Testado 2

So I want to change a whole line by using a customized function which gets as parameters the new value.所以我想通过使用自定义函数来更改整行,该函数获取新值作为参数。 The new value will always keep the first 6 characters, changing only what comes after them.新值将始终保留前 6 个字符,仅更改它们之后的字符。 Although I am testing only the first four.虽然我只测试前四个。

Then I edited my .bashrc including my function like shown below.然后我编辑了我的 .bashrc,包括我的函数,如下所示。

muda() 
{ 
export BUSCA="$(echo $* | cut -c 1-4)";
sed -i "/^$BUSCA/s/.*/$*/" ~/Documentos/texto.txt ;}

When I run the command below it works like a charm, but I feel it could be improved.当我运行下面的命令时,它就像一个魅力,但我觉得它可以改进。

muda a4a1: Testado 3

Result:结果:

cat ~/Documentos/texto.txt

65f8: Testado
a4a1: Testado 3

Is there a smarter way to do this?有没有更聪明的方法来做到这一点? Maybe by getting rid of BUSCA variable?也许通过摆脱 BUSCA 变量?

I'd write:我会写:

muda() {
    local new_line="$*"
    local key=${newline:0:4}
    sed -i "s/^${key//\//\\/}.*/${new_line//\//\\/}/" ~/Documentos/texto.txt
}

Notes:笔记:

  • using local variables, not exported environment variables使用local变量,而不是导出的环境变量
  • does not call out to cut, bash can extract a substring不调用剪切,bash 可以提取一个子串
  • escaping any slashes in the variable values so the sed code is not broken.转义变量值中的任何斜杠,以便 sed 代码不会被破坏。

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

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