Duplicate and change a column

Hi,
I have a file with list of items:

a[4]
b[4]
c[4]

I would like to run a 1-liner (awk/perl) to duplicate and change the value of the existing column, i.e.:

a[4] a[5]
b[4] b[5]
c[4] c[5]

I can duplicate with awk: awk '{print $1 " " $1 }'
but couldn't figure out how to do the character change, your help is appreciated.

Thanks!

Try

awk  '{split ($1, T, "[][]"); print $1 " "  T[1] "[" ++T[2] "]" }' file
a[4] a[5]
b[4] b[5]
c[4] c[5]
1 Like

thanks Rudi - it worked partially.
I have some entries where the brackets are not at the end like:
d[4]_s[3] which needs to change to d[5]_s[3]

Let's be clear here... RudiC's code worked perfectly for the problem you presented.

Now you have presented a different problem. And that problem is not clearly stated. We are all supposed to guess at what your real input specification is by looking at two samples. We might guess correctly or we might all be wasting our time making bad guesses.

If what you are trying to do is duplicate the contents of a line separating the original line contents from its duplicate with a <space> and if, and only if, there is a an unsigned decimal number sequence that appears between square brackets with no other characters between those square brackets somewhere on that line then replace the first occurrence of that sequence in the duplicated contents with that number incremented by one, then you might try running something like:

awk '
match($0, /[[][0-9]+[]]/) {
	print $0, substr($0, 1, RSTART) \
	    (substr($0, RSTART + 1, RLENGTH - 2) + 1) \
	    substr($0, RSTART + RLENGTH - 1)
	next
}
{	print $0, $0
}' file

which, if file contains:

a[4]
b[4]
c[4]
d[4]_s[3]
e[X]_f[99]_g[123]
f [9] g
h123[h]123123[12345678]123[j]
i[abc]_i[cde]_i[fgh]
j[z1]_2[1y]_3[1x1]

produces the output:

a[4] a[5]
b[4] b[5]
c[4] c[5]
d[4]_s[3] d[5]_s[3]
e[X]_f[99]_g[123] e[X]_f[100]_g[123]
f [9] g f [10] g
h123[h]123123[12345678]123[j] h123[h]123123[12345679]123[j]
i[abc]_i[cde]_i[fgh] i[abc]_i[cde]_i[fgh]
j[z1]_2[1y]_3[1x1] j[z1]_2[1y]_3[1x1]

Did I make a better guess, or do you think my suggestion is also partially correct?

1 Like
perl -ple '$p=$_; s/(\d+)/$1+1/e; $_="$p $_"' example

or

perl -ple '$p=$_; s/(\d+)(?=])/$1+1/e; $_="$p $_"' example
1 Like

Thanks to all the helpers.
Don - you are correct - I should have stated my problem better, didn't mean no offence by the partial comment.

This is my first post - I will check my input file and details better for the next ones.

2 Likes