Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use sed from a tcl file

Tags:

unix

sed

exec

tcl

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?

like image 494
n00b programmer Avatar asked Nov 08 '10 11:11

n00b programmer


People also ask

What is sed in TCL?

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.

How do I use sed to edit a file?

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.

How can sed be used to identify a pattern?

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.

Can sed read from stdin?

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.


1 Answers

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
like image 144
Donal Fellows Avatar answered Oct 03 '22 22:10

Donal Fellows