Replace a string in a text file

I have a text file with a line

default_color acolor 

and I want to replace this line with

 default_color anothercolor 

I do not know the first color, and the second is contained in the variable. How to do this in bash?

thanks

+4
source share
4 answers

It is not purely bash, but if you have other console tools try something like

 cat your_file | sed "s/default_color\ .*/default_color\ $VAR/" 
+7
source

You can use awk. Manual recording is here:

http://ss64.com/bash/awk.html

I will not write a regular expression, because it will depend on your color format, but it will match the score. Good luck.

0
source

use gawk

 awk '$2=="defaultcolor"{$2="anothercolor"}1' file 

or just a bash shell and external commands

 while read -r line do case "$line" in *defaultcolor*) line=${line/defaultcolor/anothercolor} esac echo $line done <"file" 
0
source

Not really a bash solution, but you can do an in-place replacement for any number of files, with perl:

perl -i -npe 's/default_color acolor/default_color another_color/' list_of_files 
-one
source

All Articles