0

this works as I expected:

$ cat in
abc 123
$ sed -E -i .bk 's/[0-9]+/(&)/' in
$ cat in 
abc (123)
$ cat in.bk
abc 123 

But not this:

$ cat in
abc 123
$ sed -E 's/[0-9]+/(&)/' in 
abc (123)
$ sed -E 's/[0-9]+/(&)/' in > in
$ cat in 

How can I modify the above set of commands such that the last command returns, instead:

abc (123)

?

5
  • Why don't you want to use -i option?
    – Toto
    Commented Sep 13, 2017 at 16:34
  • How is that helpful?
    – Erwann
    Commented Sep 13, 2017 at 16:49
  • It is not suppose to be helpfull. It's just a question, you have a command that works fine, why would you use another one?
    – Toto
    Commented Sep 13, 2017 at 18:06
  • Out of curiosity.
    – Erwann
    Commented Sep 14, 2017 at 17:52
  • 1
    Shell will first interpret redirection, so since you want to overwrite the file with >, the shell will first create the file, or if it already exists, the shell will erase it's content. When sed tries to open the file, it is already empty. The GNU sed -i option doesn't write to the file itself, instead sed creates a copy of the file and at the end rename that copy. If you edit a very big file you can see the copy file created.
    – Paulo
    Commented Sep 14, 2017 at 19:44

2 Answers 2

0
sed -i -E 's/[0-9]+/(&)/' in

Alternatively,

sed -E 's/[0-9]+/(&)/' in | tee in

overwrites the file AND gives you the output on stdout.

1
  • OK, but I don't see why ... in > in does not overwrite.
    – Erwann
    Commented Sep 14, 2017 at 17:34
1

Question: Modifying a file with sed using redirection.

Answer: obviously, the -i switch was added to sed for a reason. Just using redirection leaves you looking at a somewhat convoluted solution.

cat in | cat - | sed -E 's/[0-9]+/(&)/' > in

The following also work, but only if the input file contains a single line:

cat in | parallel 'echo {} | sed -E "s/[0-9]+/(&)/" > in'

sed -E 's/[0-9]+/(&)/' in | parallel 'echo {} >in'

Explanation: The explanation is provided by Paulo in his comment to the question (redirection is interpreted before the command is executed). My workaround is to add a level of indirection between reading the file and writing back to it.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .