Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I provide stdin to ed, which need a filename?

Tags:

linux

shell

unix

ed

Need some unix shell basic here:

For command that I see no "-" target in , say ed:

print '%-2p\nq' | ed -s FILE

Can I provide a stream from stdout of some cmd, rather than FILE name, as the data to be processed:

SomeCMD | ed -s SOMETHING_MAGICAL <<< 'print '%-2p\nq'

Is is possible?

like image 714
MeaCulpa Avatar asked Dec 12 '22 21:12

MeaCulpa


2 Answers

ed reads its commands from stdin, so if your file is also on stdin, how do you work?

In fact, you can feed file input over stdin, if you concatenate its output with a single line

i

at the beginning, to start writing in the data, then append a single . to end the input, followed by any commands. You can even output the results to stdout. Do remember that it will break if there is a line in the file with nothing but a single . in it.

So if a file input.file contains this:

First line
Second line
Third line

And a file commands.list contains this:

.
1d
1,$w /dev/stdout

Then this command line...

echo i | cat - input.file commands.list | ed -s

Will output this:

Second line
Third line

Dare I say tadaaaaa! ?

Note: you can probably protect against the case of single . lines in the file by piping the file through a filter that escapes any such lines and then unescaping them again with ed commands. I leave that to your ingenuity.

Another note: you really should use sed for this, but I couldn't let the it can't be done comments go by.

like image 90
itsbruce Avatar answered Dec 15 '22 00:12

itsbruce


You use r to read a command output into the text buffer. So, portable:

printf '%s\n' 'r !df -h' g/tmpfs/d ,p q | ed -s

or

ed -s << IN
r !df -h
g/tmpfs/d
,p
q
IN

The above reads in the output of df -h, deletes the lines matching tmpfs and prints the result.
If your shell supports process substitution:

printf '%s\n' g/tmpfs/d ,p q | ed -s <(df -h)

With gnu ed that SOMETHING_MAGICAL is called !.
As per the man page:

Start edit by reading in 'file' if given. If 'file' begins with a '!', read output of shell command.

printf '%s\n' g/tmpfs/d ,p q | ed -s '!df -h'

or, with herestring:

ed -s '!df -h' <<< $'g/tmpfs/d\n,p\nq\n'
like image 21
don_crissti Avatar answered Dec 15 '22 00:12

don_crissti