Last n characters of column as new column

Hello,
I'm looking for a short command that copies the first column to a new file, along with the last two character as a second column:

Input file (tab delimited):

9780027123227-PK        9780027123227   2        57.8505        11      100     a       n       47.8505 67.8505
9780060094584-PK        9780060094584   2        23.3325        11      100     a       n       13.3325 33.3325
9780061130243-PK        9780061130243   2        42.1755        11      100     a       n       32.1755 52.1755

Desired output (tab delimited):

9780027123227-PK     PK
9780060094584-PK     PK
9780061130243-PK     PK

Thanks!

how about:

awk '{print $1, substr($1,length($1)-1)}' OFS='\t'  myInputFile
1 Like

Hello palex,

Could you please try following.

awk '{split($1,array,"-");print $1,array[2]}' OFS="\t"  Input_file

Thanks,
R. Singh

Keep the original whitespace

sed -r 's/^(\S*(\S{2})\s*).*/\1\2/' Input_file

Use tab

sed -r 's/^(\S*(\S{2})).*/\1\t\2/' Input_file

The previous post is only for GNU sed that is compiled with a recent glibc that has got the \S \s from perl (PCRE).
If you want portability, use the original! Most commercial Unixes have got perl.

perl -pe 's/^(\S*(\S{2})\s*).*/\1\2/' Input_file

This works, but in warning mode it says

perl -wpe 's/^(\S*(\S{2})\s*).*/\1\2/' Input_file
\1 better written as $1 at -e line 1.
\2 better written as $2 at -e line 1.
9780027123227-PK        PK
9780060094584-PK        PK
9780061130243-PK        PK

Since perl 5.x it issues this warning. Fix:

perl -wpe 's/^(\S*(\S{2})\s*).*/$1$2/' Input_file
9780027123227-PK        PK
9780060094584-PK        PK
9780061130243-PK        PK

$n is like a variable that you can write ${n} (just like a variable in the shell).
Demo:

perl -pe 's/^(\S*(\S{2})\s*).*/${1}0${2}/' Input_file
1 Like