Insert a value in a pipe delimited line (unsig sed,awk)

Hi,

I want to insert a value (x) in the 3rd position of each line in a file like below

a|b|c|d|1
a|b|c|d
a|b|c|d|e|1
a|b|c

so that output file looks like

a|b|x|c|d|1
a|b|x|c|d
a|b|x|c|d|e|1
a|b|x|c

I can do that using perl as below

#!/usr/bin/perl -w
use strict;

#inserting x at pos 3

while (<>) {
        my @arr=split('\|',$_);
        my $str=join('|',@arr[0..1],'x',@arr[2..$#arr]);
        print "$str";
}

However I need to do it in sed/awk but have no idea how :eek:
help!!!

The RE can probably be condensed a bit but here is an awk version:

awk '{sub(/[^|]+\|[^|]+\|/,"&x|")}1'

...and using sed:

sed 's/\([^|]*|[^|]*|\)/\1x|/'

...or another awk way:

awk '{$2=$2"|x"}1' FS=\| OFS=\|
sed 's/|/|x|/2' file

EDIT: An alternative awk solution:

awk '{for (i=NF;i>2;i--) {$(i+1)=$i} $2="x"; print}' FS='|' OFS='|' file

But Scrutinizer's suggestion is a neater method of doing it via fields.

You can also try:

awk '{$3=s OFS $3}1' s="x" FS=\| OFS=\| file

Or

sed 's/|/|x|/2' file

*edit* CarloM beat me to it with the sed suggestion..

I knew there would be a shorter sed solution and you guys just confirmed it :smiley:

Wow!!!, thanks to all of you for your responses.
I got what I wanted :b: