0

I used following sed with character class [^[:space:]] as follows:

orig="(\`\`\`)([^[:space:]]*)"; 
new="\1{.\2 .numberLines startFrom=\"1\" .lineAnchors}"; 
sed -i -r -e "s|${orig}|${new}|g" ${InterimFilePath} ; 

Input:

```bash
ls
```

Output:

```{.bash .numberLines startFrom="1" .lineAnchors}
ls
```{.bash .numberLines startFrom="1" .lineAnchors}

Expected Output:

```{.bash .numberLines startFrom="1" .lineAnchors}
ls
```

Any suggestions? Ialso tried the character class [[:alnum:]] but the result is same as above.

1

The output I get with GNU sed and with the native sed on OpenBSD is

```{.bash .numberLines startFrom="1" .lineAnchors}
ls
```{. .numberLines startFrom="1" .lineAnchors}

This is because your expression matches zero or more non-space characters after the three backticks. Changing [^[:space:]]* into [^[:space:]]+ would force the matching of at least one non-space character.

This gives the expected output of

```{.bash .numberLines startFrom="1" .lineAnchors}
ls
```

You may also use single quotes in your variable assignments. This makes for neater looking strings without the need to escape special characters to protect them from the shell:

orig='(```)([^[:space:]]+)'
new='\1{.\2 .numberLines startFrom="1" .lineAnchors}'
sed -i -E "s|$orig|$new|g" "$InterimFilePath"
1

try this,

orig="(\`\`\`)([[:alnum:]]+)";
new="\1{.\2 .numberLines startFrom=\"1\" .lineAnchors}"; 
sed -i -r -e "s|${orig}|${new}|g" ${InterimFilePath} ; 

Output

```{.bash .numberLines startFrom="1" .lineAnchors}
ls
```
  • use + instead of *, since * will match everthing.
  • * will not "match everything", but it allows for zero matches of the previous regular expression. – Kusalananda Sep 18 '18 at 13:28

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.