【发布时间】: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 个字符