Search code examples
linuxbashtextsed

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:

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. Although I am testing only the first four.

Then I edited my .bashrc including my function like shown below.

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?


Solution

  • 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
    • does not call out to cut, bash can extract a substring
    • escaping any slashes in the variable values so the sed code is not broken.