I'm trying to use the Unix "sed" command form within a tcl file, like this: (to change multiple spaces to one space)
exec /bin/sed 's/ \+/ /g' $file
I also tried exec /bin/sed 's/ \\+/ /g' $file
(an extra backslash)
none of the version work, and I get the error
/bin/sed: -e expression #1, char 1: Unknown command: `''
The command works fine when run from a linux terminal
What am I doing wrong?
Stream Editor. A program that parses files or standard input, changes it according to a given set of rules, mostly based on Regular Expressions, and sends the new data to standard output.
Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.
Basic text substitution using 'sed'Any particular part of a text can be searched and replaced by using searching and replacing pattern by using `sed` command. In the following example, 's' indicates the search and replace task.
The sed command can read and process text from input files or standard input streams. Since our text is not saved in a file, if we can somehow write the text to stdin, then sed can read it.
What am I doing wrong?
What you're doing wrong is using '
(single quote) characters. They're not special to Tcl at all. The equivalent in Tcl is enclosing a word in {
braces}
; it gives no special treatment at all to the characters inside. Thus, what you seek to do would be:
exec /bin/sed {s/ +/ /g} $file
Mind you, if you're doing something more complex and the restriction of Tcl to whole-words being unquoted, then you might instead go for this:
exec /bin/sh -c "sed 's/ +/ /g' $file"
Or, real idiomatic Tcl just doesn't use sed for something this simple:
set f [open $file]
set replacedContents [regsub -all { +} [read $f] " "]
close $f
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With