How to extract and append in file using scrip

May 3, 2010 at 11:50:07
Specs: N/A
I have a file named "test", and content is as followings"

PRJ1_REV6788_ABC123
PRJ2_REV4567_DEF456
PRJ2_REV7891_GHI789

How to extract REV number and append it ( separated by space or tab) like this:

PRJ1_REV6788_ABC123 6788
PRJ2_REV4567_DEF456 4567
PRJ2_REV7891_GHI789 7891

Any reply is appreciated!


See More: How to extract and append in file using scrip

Report •

#1
May 3, 2010 at 15:14:34
One way is an awk script which assumes a Field Separator as an underscore. I take a copy of the 2nd field and remove the REV string. Then, copy the entire string and the modified 2nd field:

#!/bin/bash

awk ' BEGIN {  FS="_" } {
str=$2
# get rid of the REV
gsub(/REV/,"",str)
printf("%s %s\n", $0, str)
} ' test


Report •

#2
May 3, 2010 at 15:25:53
Better yet, use a regular expression to eliminate any alpha characters - not just REV:

#!/bin/bash

awk ' BEGIN { FS="_" } {
str=$2
# get rid of the rev
gsub("[a-zA-Z*]","",str)
printf("%s %s\n", $0, str)
} ' test


Report •

#3
May 5, 2010 at 05:28:52
perl -pi.bak -e '$_ =~ s/^(.+REV)(\d+)(.+)$/$1$2$3 $2/' test


Report •
Related Solutions


Ask Question