Identify the First Column Position in Second Column and add the position value

Identify the First Column Position in Second Column and add the position value in 3rd column.


Sample data:
a|c
b|d
c|a
d|b
e|e
f|g
g|f
  |h
  |i
Expected Output:

a|c|1
b|d|2
c|a|3
d|b|4
e|e|5
f|g|6
g|f|7
  |h|
  |i|

Something like this?

awk -F\| '{NF=3}$1 ~ /[a-zA-Z]/{$3=NR}1' OFS=\| file

No. the current command giving sequence.. of each row I'm not looking like that. The output should be like this

a|c|3      explanation: means -- column-1 value "a" presents in column-2 at 3 position
b|d|4      explanation: means -- column-1 value "b" presents in column-2 at 4 position
c|a|1      explanation: means -- column-1 value "c" presents in column-2 at 1 position
d|b|2      explanation: means -- column-1 value "d" presents in column-2 at 2 position
e|e|5      explanation: means -- column-1 value "e" presents in column-2 at 5 position
f|g|7       explanation: means -- column-1 value "f" presents in column-2 at 7 position
g|f|6       explanation: means -- column-1 value "g" presents in column-2 at 6 position
  |h|        
  |i|

if the column-1 value doesn't exists in column - put # in it.

Hello BrahmaNaiduA,

Could you please try following and let me know if this helps.

awk -F"|" '{if($1 !~ /^[[:space:]]+/){$(NF+1)=NR} else {$NF=$NF"|"}} 1' OFS="|" Input_file

Output will be as follows.

a|c|1
b|d|2
c|a|3
d|b|4
e|e|5
f|g|6
g|f|7
  |h|
  |i|

Thanks,
R. Singh

the output is not in the expected format.

Expected Output:
a|c|3
b|d|4
c|a|1
d|b|2
e|e|5
f|g|7
g|f|6
k|h|9
 |i|
 |k| 

Column 3: explanation for your understanding:

column-1 value "a" presents in column-2 at 3 position
column-1 value "b" presents in column-2 at 4 position
column-1 value "c" presents in column-2 at 1 position
column-1 value "d" presents in column-2 at 2 position
column-1 value "e" presents in column-2 at 5 position
column-1 value "f" presents in column-2 at 7 position
column-1 value "g" presents in column-2 at 6 position
column-1 value "k" presents in column-2 at 9 position

Thanks,
Brahma

Why, then, don't you specify your request correctly in the first place?

Anyhow, try

awk 'NR==FNR {T[$2]=NR;next} {print $0 FS (T[$1]?T[$1]:"#")}' FS="|" file file
a|c|3
b|d|4
c|a|1
d|b|2
e|e|5
f|g|7
g|f|6
  |h|#
  |i|#

Hello,

Could you please try following, it may help you.

awk -F"|" '{split("abcdefghijklmnopqrstuvwxyz", A,"")} {for(i in A){if($2==A && $1 !~ /^[[:space:]]/){$(NF+1)=i;};}if($1 ~ /^[[:space:]]+/){$2=$2"|#"}} 1' OFS="|" Input_file

Output is as follows.

a|c|3
b|d|4
c|a|1
d|b|2
e|e|5
f|g|7
g|f|6
  |h|#
  |i|#

EDIT: Please always be clear in your requirements, as per your first post I have posted my previous solution.

Thanks,
R. Singh

1 Like