【问题标题】:bash: How to replace an entire line in a text file by a part of its contentbash:如何用部分内容替换文本文件中的整行
【发布时间】:2021-12-18 22:18:16
【问题描述】:

我在 Documentos 文件夹中有一个名为 texto.txt 的文本文件,其中的一些值如下所示:

cat ~/Documentos/texto.txt

65f8: Testado
a4a1: Testado 2

所以我想通过使用自定义函数来更改整行,该函数将新值作为参数。 新值将始终保留前 6 个字符,仅更改其后的内容。虽然我只测试前四个。

然后我编辑了我的 .bashrc,包括如下所示的函数。

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

当我运行下面的命令时,它就像一个魅力,但我觉得它可以改进。

muda a4a1: Testado 3

结果:

cat ~/Documentos/texto.txt

65f8: Testado
a4a1: Testado 3

有没有更聪明的方法来做到这一点?也许通过摆脱 BUSCA 变量?

【问题讨论】:

  • 您确定 sed 行中没有 $ 吗?
  • 抱歉,打错了。已经调整好了,谢谢
  • 使用 `muda() {export BUSCA="${1}"; 消除对 $(echo ... | cut ...) 的 2 个子进程调用转移; sed -i "s/^${BUSCA}.*/${BUSCA} $*/" ~/Documentos/texto.txt;}; if you know for a fact that you can trust the format of the input a further simplifcation: muda() { sed -i "s/^$1.*/$ */" texto.txt;}`
  • 我需要剪切以仅使用前 4 个字符

标签: linux bash text sed


【解决方案1】:

我会写:

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

注意事项:

  • 使用local 变量,而不是导出的环境变量
  • 不调用剪切,bash 可以提取子字符串
  • 转义变量值中的任何斜线,这样 sed 代码就不会被破坏。

【讨论】:

  • 很好,我喜欢这个,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-24
  • 1970-01-01
  • 2018-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-10
相关资源
最近更新 更多