Operating System - HP-UX
1826313 Members
4036 Online
109692 Solutions
New Discussion

Re: Editing n-1th occurrence of a character in a file

 
SOLVED
Go to solution
cbres00
Frequent Advisor

Editing n-1th occurrence of a character in a file

Some of you may remember my posts from last week regarding swapping a slash with a pipe in a file. While I got a successful resolution to that particular problem, I found a new problem with a different file.

In a nutshell, every record in my pipe-delimited file can have one or more slashes, the first one(s)one occurring in the very first field, and the last slash occuring in the last field. I need to preserve the last slash, but convert the next-to-last slash to a pipe.

Ex:
(spaces added for emphasis)

aa/bb/cc /dd| ee|ff|gg|/hh|

I need to change this to:
aa/bb/cc |dd| ee|ff|gg|/hh|

The solution I got from this wonderful community works for the first example but not the second:

while
read input_record
do
start=${input_record%/*}
last=${input_record##*/}
print "$start|$last" >> ${output_file}
done < ${input_file}

Could this code be easily changed to accomodate my needs?

Regards,
Cathy


Life is too short not to have fun every single day
4 REPLIES 4
curt larson_1
Honored Contributor
Solution

Re: Editing n-1th occurrence of a character in a file

if you just want to modify what you have

while
read input_record
do
Last=${input_record#*|} #everything after the first |
Start=${input_record%%|*} #everything before the first |

start=${Start%/*} # everything before the last / in $Start
last=${Start##*/} # everything after the last / in $Start

print "$start|$last|$Last" >> ${output_file}
done < ${input_file}
curt larson_1
Honored Contributor

Re: Editing n-1th occurrence of a character in a file

but now sed and perl become a bit more useful

sed 's!\([^|]*\)/\(.*|.*\)/\1|\2!'

replaces the last / before the first | with |
cbres00
Frequent Advisor

Re: Editing n-1th occurrence of a character in a file

Curt,
Sometimes the solution is SO simple it's easy to miss! I like your first solution simply because it's more readable for the developer who may need to modify this in the future.

Superb work! Many thanks (and points!!).

Cathy
Life is too short not to have fun every single day
cbres00
Frequent Advisor

Re: Editing n-1th occurrence of a character in a file

One minor correction:

I wasn't getting anything out of $Last or $Start. I neutralized the pipe and got results:

Last=${input_record#*\|}
Start=${tactic_state_record%%\|*}

Thanks again!
Cathy
Life is too short not to have fun every single day