taT4Nix | Search and Replace Nth Delimited Item

Recently, somebody asked whether it’s possible to replace Nth delimited item, delimiter set as pipe symbol. Suppose, the text contains;

TXT="abc|def|ghi|jlk|mnop|qrst|uvw|xyz|123|456|7890"

Now, if you look at the text, 4th delimited item is out-of-order, i.e jlk. So, if I want to correct it to jkl, (i.e. N = 4) I tried solving this using sed and found complex solution;

echo $TXT | sed -r 's/((([^|]*)\|){3})([^|]*)(.*)$/\1jkl|\5/'
## General Solution
typeset -i N=$1; (( N-- ))
cat $2 | sed -r 's/((([^<delimiter>]*)<delimiter-with-or-without-esc-seq>){'$N'})([^<delimiter>]*)(.*)$/\1<replace-pattern><delimiter>\5/'

Few days later, my colleague suggested the following solution, rather easy one;

echo $TXT | sed -r 's/[^|]*/jkl/4'
## General Solution
typeset -i N=$1
cat $2 | sed -r 's/[^<delimiter>]*/<replace-pattern>/'$N''

Both of them worked, the later one was easy to read and explain.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s