Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

newbie question about sed and awk....

Status
Not open for further replies.

cmfwork

Technical User
Aug 18, 2000
5
0
0
US
How do I write to a file using sed and/ or awk.
My problem. I have a file that needs to be updated after and install. I want to script into the installation script to get the input from the user and plop that into the config file.
I can get the line number that I want to change by doing a sed command (sed -n -e /foo/= conf.file > linenum.file) and then reading the line num into a variable. I just don't know how to write the data that I need to write on that line number.

This is my test script so far:
echo "enter some text to write to file here:"
read enteredtext
sed -n -e /foo/= conf.file > linenum.file
read lineNum <linenum.file
# Now I have no clue as to what to do...
# I know that I have to stick foo at the beginning of the
# line that I am inserting (foo <entered text>)
any help? Idea? Am I doing things completely wrong... I know there has to be a better way to accomplish what I am doing
Thanks
-cmf
 
The general Unix text commands work its's files sequentially, then normally you have to create another modified file and the mv the files around; try this:
[tt]
awk '/Found text/ ~ $0 { print bEfOrE_tExT $0 } ; /Found text/ !~ { print $0 }' < TheFile > TheFile_modified
rm TheFile
mv TheFile_modified TheFile
[tt]

I hope it works...
 
Help!!! I am getting the following error now...
awk: Syntax error Context is:
>>> ~ $0 { print bEfOrE_tExT $0 } ; /Found text/ !~ { <<<

Thanks
-CMF
 
sed &quot;${NUM}s/^.*/foo &/&quot; < file > file.new
mv file.new file

sed instructions explained: -

Contain the sed commands in double quotes so the the $NUM variable can be interpreted.

$NUM is the line number variable, put {} around NUM to show that the following s is not part of the variable name.

/^.*/ is intepreted as replace all text from the start of line.

/foo &/ means insert &quot;foo &quot; before text to be replaced, & says put the text to be replaced here.
 
Oops! Sorry

With [tt]awk[/tt] your are telling: When you found a line ($0) with text [tt]Found text[/tt] then print some text and then the line. When you found a line without [tt]Found text[/tt] then print only the line... change the sentences to
[tt]
/Found text/ !~ $0 { print $0 }
[/tt]

... everything else can must be the same.

I hope it works...
 
thanks everyone... this has been truly helpful...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top