Martin Trigaux
Martin Trigaux

Reputation: 5401

Replace a line in a text file

I've a text file with a line

default_color acolor

and I want to replace this line with

default_color anothercolor

I don't know the first color and the second is contained in a variable. How can I do it in bash ?

Thank you

Upvotes: 4

Views: 3541

Answers (4)

Idelic
Idelic

Reputation: 15572

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

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

Upvotes: -1

ghostdog74
ghostdog74

Reputation: 342263

use gawk

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

or just bash shell and no external commands

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

Upvotes: 0

Will Barrett
Will Barrett

Reputation: 2647

You could use awk. The manual entry is here:

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

I won't write the regular expression necessary, as that will depend on your color format, but this will fit the bill. Best of luck.

Upvotes: 0

Dmitry
Dmitry

Reputation: 3780

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

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

Upvotes: 7

Related Questions