3

Here's a sample 'test.txt'

abcdX1yad45das
abcdX2fad45das
abcdX3had45das
abcdX4wad45das
abcdX5mad45das

sample desired output:

X1yad
X2fad
X3had
X4wad
X5mad

I could get it working in vim with:

:% s/\v.*(X\d)(.*)45.*/\1\2/

and worked in perl as well with:

open(my $file, "<", "test.txt");
while(<$file>)
{
    s/.*(X\d)(.*)45.*/$1$2/; 
    print $_;
}

my eventual regular expression needs two groupings, it wasn't required for this example output

am not able to get it work with sed:

sed -r 's/.*(X\d)(.*)45.*/\1\2/' test.txt
abcdX1yad45das
abcdX2fad45das
abcdX3had45das
abcdX4wad45das
abcdX5mad45das

just to check sed is working,

sed -r 's/(a)/#\1#/' test.txt
#a#bcdX1yad45das
#a#bcdX2fad45das
#a#bcdX3had45das
#a#bcdX4wad45das
#a#bcdX5mad45das

what am I doing wrong in sed?

5

sed does not understand \d. You can use [0-9] or, more generally, [[:digit:]] in its place:

$ sed -r 's/.*(X[[:digit:]])(.*)45.*/\1\2/' test.txt
X1yad
X2fad
X3had
X4wad
X5mad

Note that [[:digit:]] is unicode-safe but [0-9] is not.

  • 1
    thanks, I think I've come across this before and forgot... – Sundeep Apr 27 '16 at 5:27
  • 1
    @spasic : On the contrary, vim do understand [[:digit:]] & [0-9]. You might wish to stick on with one format – sjsam Apr 27 '16 at 6:57
  • 1
    yup, will keep this in mind.. but hard to change years of usage – Sundeep Apr 27 '16 at 8:02
  • Note \d and [[:digit:]] are the same, but [0-9] is different in (e.g.) Unicode where there are digit codepoints that are not within [0-9]. – abligh Apr 27 '16 at 10:53
1
sed 's/abcd\(X[0-9][a-z]ad\)45das/\1/g' your_file_name

should do it.

0

You sed does not understand the special sequence \d. Replace \d with [0-9] or character class [:digit:]:

$ cat file.txt
abcdX1yad45das
abcdX2fad45das
abcdX3had45das
abcdX4wad45das
abcdX5mad45das

$ sed -nr 's/.*(X\d)(.*)45.*/\1\2/p' file.txt   

$ sed -nr 's/.*(X[0-9])(.*)45.*/\1\2/p' file.txt
X1yad
X2fad
X3had
X4wad
X5mad

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.