2

I want to replace strings which contain tilde character of varying lengths with strings of spaces. For example, if a string contains 5 tilde characters: ~~~~~, then I want to replace it with 5 spaces.

My current sed command:

sed -e '/\\begin{alltt}/,/\\end{alltt}/s/~\+/ /' test.tex

I can check for one or more tilde characters, but don't know how to retrieve the length to insert the spaces

2
  • 1
    Refer this link , it might be of help. Commented Feb 21, 2017 at 13:24
  • 4
    Is s/~/ /g not an option? Or do you need to replace only the first sequence of ~s on a line? Commented Feb 21, 2017 at 13:26

1 Answer 1

5
sed '/\\begin{alltt}/,/\\end{alltt}/s/~/ /g'

Would replace all the ~s with spaces. If you wanted to replace only the ~s from the first sequence of ~s on each line, you could do:

sed '
  /\\begin{alltt}/,/\\end{alltt}/{
    /~/ {
      h; # save a copy
      s/\(~\{1,\}\).*/\1/; # remove everything after the first sequence of ~s
      s/~/ /g; # replace ~s with spaces
      G; # append the saved copy
      s/\n[^~]*~*//; # retain only what's past the first sequence of ~s
                     # from the copy
    }
  }'

Note: \{1,\} is the standard equivalent of your \+ GNU extension.

It's easier with perl:

perl -pe 's{~+}{$& =~ s/~/ /gr}e if /\\begin\{alltt\}/ .. /\\end\{alttt\}/'

or:

perl -pe 's{~+}{" " x length$&}e if /\\begin\{alltt\}/ .. /\\end\{alttt\}/'
1
  • Oh yes. It should be ~, not ~\+ that matches the whole thing to be replaced. Commented Feb 21, 2017 at 14:32

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.