Hey guys, i am about to throw it all in because i just cannot get this to work :S.

All i wanted to do is search through a file and find a string and replace with an argument from the command line.

So basically i have a file which has the contents of :

this is a test file
yes i am cool

say if i want to replace cool with $1 (which is 'crap', an argument from the shell) how do i accomplish this?

So far i have $1 = awk '/yes/ { print $4 }' file > file

I then want to overwrite the file with the updated contents. So the contents of file look like this:

this is a test file
yes i am crap

This just doesnt seem to do the job. If anyone knows please help!! i wont have any fingernails left soon :P thanks guys.

Recommended Answers

All 3 Replies

/bin/echo "%s/cool/$1/g\nwq!" | ex -s file

Member Avatar for varkey

in awk it divides the line into fields .. so u can seperate yes i am cool in such a way that $1 represents yes,$2 for I ,$3 for am and $4 for cool...

/bin/echo "%s/cool/$1/g\nwq!" | ex -s file

#!/usr/bin/bash
arg=$1
awk -v var=$arg '{  gsub(/yes/,var,$0); print  }' file

output:

#./test.sh
this is a test file
crap i am cool
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.