1

I have a file with ~1000 rows here is the first few rows:

head file.regions.txt
cregions1
cregions2
cregions3
cregions4
cregions5
cregions6
cregions7
cregions8
cregions9
cregions10
...

I want to add brackets around the numbers and also "<-" for each row after numbers! This is my desired output

head file.regions.output.txt
    cregions[1] <-
    cregions[2] <-
    cregions[3] <-
    cregions[4] <-
    cregions[5] <-
    cregions[6] <-
    cregions[7] <-
    cregions[8] <-
    cregions[9] <-
    cregions[10] <-
    ...
0

2 Answers 2

3

How about

sed -e 's/$/] <-/g' -e 's/cregions/cregions[/g' yourFile
1

You can use:

sed -r 's/^(cregions)([0-9]+)$/\1[\2] <-/' file.regions.txt >file.regions.output.txt

Note that this doesn't add any leading tabs or spaces. (You didn't mention that in your problem description, but your output example seems to have them.)

This only changes lines whose entire contents is cregionsN, with one or more digits in place of N. If you want to apply the transformation to any line that ends in one or more digits, you can use this simpler sed command instead:

sed -r 's/[0-9]+$/[&] <-/' file.regions.txt >file.regions.output.txt

(Thanks to glenn jackman for pointing out that this version of the command does not need capture groups because it can simply use &, which represents the entire match.)

With either of these commands, you can of course see the output instead of writing it to a file by omitting the >file.regions.output.txt redirection.

1
  • 1
    You don't need to capture: sed -r 's/[0-9]+$/[&] <-/' -- the & in the replacement side is replaced by all the text that was matched. Commented Jun 19, 2019 at 14:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .