I have data of the following format that I want to input into LibreOffice calc

data | num   | num | num     | num

For some reason Libreoffice does not think the string "3214 " is a number by default (trailing white space).

I want to replace (\s)*| with | where \s stands for space and * for the Kleene star operation. And do this at multiple places in each line (all matches).

I tried:

sed  -i 's/(\s)*|/|/' DataStats0914.txt

But it has no effect.


Why would you quote it? If you want references, use \( and \) instead,

Also, note the g option, since that pattern apperas multiple times

sed -i 's/\s*|/|/g' DataStats0914.txt

Test case:

echo 'data | num | num | num | num' | sed 's/\s*|/|/g'


data| num| num| num| num

  • laziness of manual reading is the reason. But frankly the man pages intimidate me.
    – Erik
    Oct 25 '12 at 4:17

There are several different regular expression syntaxes. (\s*) matches a sequence of whitespace in Perl and the many other modern programs that imitate its regexes. Sed uses an older variant of basic regular expressions in which parentheses stand for themselves and \(…\) is used for grouping. GNU sed (the version on Linux) has an option -r to use extended regular expressions (which Perl regexes extend further) instead. Also, | stands for itself in BRE but must be preceded by a backslash in ERE.

s/[ \t]\+|/|/ replaces whitespace followed by a | with GNU sed. If you want a POSIX-compliant sed command, use s/[ ][ ]*|/|/ where each pair of brackets contains a space and a tab, as \t and \+ are GNU extensions. Also, the s command only replaces one occurrence per line: add the g suffix to replace all occurrences.

sed  -i 's/[ \t]\+|/|/g' DataStats0914.txt

sed removing spaces:

sed -i 's/ *|/|/g' file

Pythonish three liner, untested:

python -c 'import sys
for l in sys.readlines():
    print("| ").join([f.strip() for f in l.strip().split("|")])'

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.