1

How could I copy digits from one end of a string to another end of a string? So example,

Input -

Example123:Hello
Exp12:Hey1
Exp:heylo

expected output -

Example123:Hello123
Exp12:Hey112
Exp:heylo

I'm open to using sed or awk, seperator must be accounted for, so row1 is the row to extract digits from and row 2 is the row to place digits

Sparhawk
  • 19,941

5 Answers5

3

Assuming there's one and only one occurrence of : in each line of the input, you could do something like:

sed 's/\([[:digit:]]*\):.*/&\1/' < input

If there can be more than one : (and you want to append the digits to the end of the line, not the second field), that becomes more complicated, like:

sed 's/^\([^:]*[^:[:digit:]]\)\{0,1\}\([[:digit:]]*\):.*/&\2/' < input
2

You can use awk here

awk -F':' '{ j=$1; gsub(/[^0-9]+/,"",j); print $0 j }' 

Explanation

-F':': tells awk to use colon as the field separator

j=$1; gsub(/[^0-9]+/,"",j) : assigns the first column to to a temporary variable j, and then removes anything that is not a digit from j

print $0 j : finally prints the original string appended with j that carries our number

amisax
  • 3,025
1

With the match() function of GNU awk to store the matching group in an array, you could do

awk -F: -v OFS=: 'match($1, /([0-9]+)$/ , arr) { $2 = $2 arr[1] } 1' file

On any POSIX compliant awk you could do

awk -F: -v OFS=: 'match($1, /[[:digit:]]+$/) { $2 = $2 substr($0, RSTART, RLENGTH) }; 1' file

See How to permanently change a file using awk? ("in-place" edits, as with "sed -i") to make the file change persistent.

Inian
  • 12,807
0

Tested with below script and worked fine

Count_line=`awk '{print NR}' filename| sort -nr| sed -n '1p'`

for ((i=1;i<=$count_line;i++)); do awk -v i="$i" -F ":" 'NR==i{print $1}' filename| grep -o "[0-9]$">/dev/null; if [[ $? == 0 ]]; then h=`awk -v i="$i" -F ":" 'NR==i{print $1}' filename|grep -o "[0-9]*$"`; awk -v i="$i" -v h="$h" 'NR==i{print $0h}' filename; else awk -v i="$i" 'NR==i{print $0}' filename; fi; done

output

Example123:Hello123
Exp12:Hey112
Exp:heylo
0

As short as possible in bash... I think...

sed 's/\([0-9]\+:\).*/&\1/' < input

(With a bit a help from @Stèphane's earlier answer.)

David Yockey
  • 1,834