Fibo Kowalsky
Fibo Kowalsky

Reputation: 1248

Prepend a subtext of a line to the same line

How to get from the file:

This is a line 2
There is 1 line
imagine 3 lines
two times two is 4
There is no number here

The following:

2, This is a line 2
1, There is 1 line
3, imagine 3 lines
4, two times two is 4

So, the prefix is retrieved from the line and it can vary from line to line. How this can be done in bash and perl? Roughly like this:

s/\d+/$&, $`$&$'/

Upvotes: 0

Views: 92

Answers (3)

jaypal singh
jaypal singh

Reputation: 77095

Using bash from the command line:

$ while read -r line; do 
    [[ $line =~ [0-9]+ ]] && echo "${BASH_REMATCH[0]}, $line"; 
done < file
2, This is a line 2
1, There is 1 line
3, imagine 3 lines
4, two times two is 4

Upvotes: 2

Miller
Miller

Reputation: 35198

Using a perl one-liner

perl -ne 'print "$1, $_" if /(\d+)/' filename

Switches:

  • -n: Creates a while(<>){...} loop for each “line” in your input file.
  • -e: Tells perl to execute the code on command line.

Upvotes: 3

Cyrus
Cyrus

Reputation: 88583

sed -En 's/.*([0-9]+).*/\1, &/p' filename

Upvotes: 2

Related Questions