Replace a line in a bash script file

1

The situation is as follows, I have 3 variables available:

numlinha - > line number to replace

texto - > text of the line to be replaced (I would prefer to use the line number but this is here if I can)

texto_sub - > text that is going to be replaced

The purpose is to replace a line of the file file.txt, if I can, I can use another search variable instead of the entire line.

I tried to do something like sed -i '/$texto/c\$texto_sub' file.txt but it does not work in bash script. The ideal solution for me was to replace with the line number but nothing I tried and saw worked.

    
asked by anonymous 04.10.2018 / 21:05

3 answers

1

Use this sed option:

sed '17s/string/newstring/' file

where '17' is the line number to replace If you already want to change the file directly, include the -i

    
05.10.2018 / 14:27
0

With Sed you can do good, but I prefer to use variables ( if text is short ) as follows.

Contents of the .txt file

cat arquivo.txt
aaa bbb ccc
111 222 333
ddd hhh iii

I will assume that the variables are already declared.

textoantigo="111 222 333"
textonovo="buuuuuuuuuu"
txt_all=$(cat arquivo.txt)
txt_all=${txt_all/$textoantigo/textonovo}
echo "$txt_all" > arquivo.txt

How did it go.

cat arquivo.txt
aaa bbb ccc
buuuuuuuuuu
ddd hhh iii

Remember, beware of the size of the file to put inside a variable.

    
09.10.2018 / 21:33
0

other ex:

cat file.txt

test line1

test line2

test line3

awk 'NR == 2 {sub ($ 0, "newline")} 1' file.txt

test line1

new line

test line3

NR Contains the current record number (line number)

sub The "sub" function is used to replace one string with another

$ 0 integer record (takes all the contents of the line in question)

"new line" new text that will replace the old one

1 For awk the '1' is seen as true and therefore is equivalent to printing

    
22.10.2018 / 04:53