Regex or Sed
Hi, I need to perform a simple substitution by replacing whitespaces with a character but only within the middle of a specific identifiable patterns. For example, if I have the following:
Name, Sex, Address Tom, M, 15 Broadway Mary, F, 80 Maple Street I need to transform it to the following (not in Excel but with command lines please) by adding hyphens to the address field. It can be anything but this is just an example. Name, Sex, Address Tom, M, 15-Broadway Mary, F, 80-Maple-Street I need to have the flexibility of specifying some type of pattern to frame where I want the translation or replacement to take place. In this case: Start Pattern = ^.*,\s(M|F),\s Stop Pattern = $ Can someone please show me how this can be done? Thanks. Thought about using sed but it can do only the whole line as far as I know and not a portion of the line. Not sure how to use regex to replace aside from specifying start and stop patterns. |
Code:
echo "Mary, F, 80 Maple Street" | sed -r 's/([^,])[ ]/\1-/g' Code:
-r - use regular expression Code:
echo "Mary, F, 80 Maple Street" | sed -r 's/([^,])[ ]/-/g' Code:
[ ] - space eventually you can use [ ]* for multiple spaces Code:
echo "Mary, F, 80 Maple Street" | sed -r 's/([^,])[ ]/\1-/' |
Hi.
Here is awk approach: Code:
$ cat in |
OP has this input file:
Code:
$ cat in Code:
$ awk '{gsub(" +", "-", $3);}1' FS=' *, *' OFS=, in Code:
Name, Sex, Address Code:
Name, Sex, Address Code:
awk '{gsub(" +", "-", $3);}1' FS=' *, *' OFS=', ' $InFile |
Quote:
You can easily enough incorporate his "condition", too: Code:
echo "Name, Sex, Street Address fact that the condition works ;} Cheers, Tink |
A couple of the proposed solutions in this thread took "80 Maple" and turned it into "8-Mapl". A 0 and an e were lost. That isn't right, is it?
Daniel B. Martin |
Quote:
the output of the command I quoted against the input, and blindly assuming it did what was needed :) Code:
echo "Name, Sex, Street Address Cheers, Tink |
All times are GMT -5. The time now is 10:34 AM. |