user2433937
user2433937

Reputation: 65

replacing strings in a configuration file with shell scripting

I have a configuration file with fields separated by semicolons ;. Something like:

user@raspberrypi /home/pi $ cat file  
string11;string12;string13;
string21;string22;string23;
string31;string32;string33;

I can get the strings I need with awk:

user@raspberrypi /home/pi $ cat file | grep 21 | awk -F ";" '{print $2}' 
string22

And I'd like to change string22 to hello_world via a script.

Any idea how to do it? I think it should be with sed but I have no idea how.

Upvotes: 2

Views: 1161

Answers (3)

Vijay
Vijay

Reputation: 67211

Even though we can do this in awkeasily as Sudo suggested i prefer perl since it does inline replacement.

perl -pe 's/(^[^\;]*;)[^\;]*(;.*)/$1hello_world$2/g if(/21/)' your_file

for in line just add an i

perl -pi -e 's/(^[^\;]*;)[^\;]*(;.*)/$1hello_world$2/g if(/21/)' your_file

Tested below:

> perl -pe 's/(^[^\;]*;)[^\;]*(;.*)/$1"hello_world"$2/g if(/21/)' temp
string11;string12;string13;
string21;"hello_world";string23;
string31;string32;string33;
> perl -pe 's/(^[^\;]*;)[^\;]*(;.*)/$1hello_world$2/g if(/21/)' temp
string11;string12;string13;
string21;hello_world;string23;
string31;string32;string33;
> 

Upvotes: 1

Chris Seymour
Chris Seymour

Reputation: 85775

First drop the useless use of cat and grep so:

$ cat file | grep 21 | awk -F';' '{print $2}'

Becomes:

$ awk -F';' '/21/{print $2}' file

To change this value you would do:

$ awk '/21/{$2="hello_world"}1' FS=';' OFS=';' file 

To store the changes back to the file:

$ awk '/21/{$2="hello_world"}1' FS=';' OFS=';' file > tmp && mv tmp file

However if all you want to do is replace string22 with hello_world I would suggest using sed instead:

$ sed 's/string22;/hello_world;/g' file

With sed you can use the -i option to store the changes back to the file:

$ sed -i 's/string22;/hello_world;/g' file

Upvotes: 2

Birei
Birei

Reputation: 36252

I prefer better than . Here a one-liner that modifies the file in-place.

perl -i -F';' -lane '
    BEGIN { $" = q|;| } 
    if ( m/21/ ) { $F[1] = q|hello_world| }; 
    print qq|@F|
' infile

Use -i.bak instead of -i to create a backup file with .bak as suffix.

It yields:

string11;string12;string13
string21;hello_world;string23
string31;string32;string33

Upvotes: 2

Related Questions