Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print the first number from line followed by tab and the line without the number

Tags:

regex

sed

I am having a hard time doing this task with sed.

Sample Input:

X(996002) dsafsafdsfdsfds dsfdsfds dsfd ds
Y(300342) dsfdsfhdsfhsa dsf;dsjfds f 15 16 .
"(1200479) dsfkjdsfhjfds dsfdsj sd "

Sample Output:

996002 TAB ) dsafsafdsfdsfds dsfdsfds dsfd ds
300342 TAB ) dsfdsfhdsfhsa dsf;dsjfds f 15 16 .
1200479 TAB ) dsfkjdsfhjfds dsfdsj sd "

So far I have the following with sed:

sed -e 's/^.*\([0-9]*\)\(.*?\)$/\1 \t \2/gp' textfile.txt

but I think I don't understand something to make it work.

like image 765
coneyhelixlake Avatar asked Dec 29 '25 21:12

coneyhelixlake


2 Answers

You can use:

sed -i.bak 's/^[^[:digit:]]*\([[:digit:]]\+\)/\1\t /' file
996002   ) dsafsafdsfdsfds dsfdsfds dsfd ds
300342   ) dsfdsfhdsfhsa dsf;dsjfds f 15 16 .
1200479  ) dsfkjdsfhjfds dsfdsj sd "

Explanation:

  • -i.bak - Inline editing, save original file with .bak extension
  • ^ - match linse start
  • ^[^[:digit:]]\+ - match 1 or more non-digits at start
  • \(...\) - Group enclosed content into a captured group #1
  • \([[:digit:]]\+\) - Capture 1 or more digits in group #1
  • \1\t - Replace by group #1 followed by a tab and a space
like image 172
anubhava Avatar answered Jan 01 '26 13:01

anubhava


does this work for you?

 sed 's/.*(\([^)]*\)/\1\t/' file

with your input file:

kent$  cat f
X(996002) dsafsafdsfdsfds dsfdsfds dsfd ds
Y(300342) dsfdsfhdsfhsa dsf;dsjfds f 15 16 .
"(1200479) dsfkjdsfhjfds dsfdsj sd "

kent$  sed 's/.*(\([^)]*\)/\1\t/' f
996002  ) dsafsafdsfdsfds dsfdsfds dsfd ds
300342  ) dsfdsfhdsfhsa dsf;dsjfds f 15 16 .
1200479 ) dsfkjdsfhjfds dsfdsj sd "
like image 44
Kent Avatar answered Jan 01 '26 12:01

Kent



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!