Replace a line from a bash script file

Asked

Viewed 538 times

1

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

numlinha -> line number to be replaced

texto -> line text that will be replaced(I would prefer to use the line number but this is here if it works better)

texto_sub -> text that will be replaced

The goal is to replace a line in the file.txt, in case it works I can also 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 doesn’t work in the bash script. The ideal solution for me was to replace with the line number but nothing I tried and saw worked.

3 answers

1

Use this sed option:

sed '17s/string/newstring/' file

where '17' is the row number to replace If you already want to exchange directly in the file, include the -i parameter

0

another ex:

cat file.txt

line test1

Linha2 test

line test3

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

line test1

new line

line test3

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 row in question)

"new line" new text that will replace the old

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

0

With the Sed you can do well, but I prefer to use variables (if the 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

as it turned out.

cat arquivo.txt
aaa bbb ccc
buuuuuuuuuu
ddd hhh iii

Remember, be careful with the file size for you to put inside a variable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.