The UNIX and Linux Forums  

Go Back   The UNIX and Linux Forums > Top Forums > UNIX for Dummies Questions & Answers
Google UNIX.COM



View Single Post in UNIX Forums - Click on the Thread or Permalink to View Entire Thread -->
  #3 (permalink)  
Old 10-29-2006
Heathe_Kyle Heathe_Kyle is offline
Registered User
 

Join Date: Oct 2006
Posts: 15
While I'm sure that awk can do that, the first thing I thought of when I read your problem was to use sed. Try this:

# sed 's/^/Will India win the /g' file > file1
# mv file1 file
# sed 's/$/ Cup/g' file > file1
# mv file1 file

sed is a good tool when you need to make several simple edits to a text file. In this case, here is what my code does:

First, the general format of a sed command is:

# sed <some commands> <file to edit>

The 's/^/Will India win the /g' file says:
s - substitute
^ - This is the regular expression that means "The beginning of the line".
Will India win the - These are the words that need to go in front of "World".
g - globally. If you do not specify this, sed will apply the change you are asking for only to the first line that matches the regular expression. Using a g here means make that change everywhere (in this case, everywhere means "every line").

The end of the line has "file > file1". When using text processing commands like sed, awk, grep, shell, and perl, it is V-E-R-Y important that you do not redirect the output right back into the file from which you are reading. For example: never do this -

sed some commands file > file

That will cause all kinds of weird stuff to happen. The solution is to store the output of a command to another file, then use the mv command to rename the new file back to the old one.

So, putting it all together:

# sed 's(ubstitute)/^(at the beginning of the line)/(all the stuff between these two forward slashes)Will India win the /g(lobally)' file >(store the output into) file1(or whatever you want to call the second file).

I'm guessing you can figure out the second sed command. The $ is the regular expresion that means "the end of the line". Between these 4 commands, that should do what you want.

So that's how I would do that in sed. I am curious, can anyone explain how to do that in awk?
Reply With Quote