Hot to replace the stdout the last line of the last control character via sed command?

Viewed 42

I wanna replace(delete) the last line of the last control character newline form ls command stdout result. Which I had try sed command is :

ls | sed '$ s/[[:cntrl:]]$//'
ls | sed '$ s/[[:graph:]]$//'
ls | sed '$ s/[[:print:]]$//' 

The result I want like this result ls | head -c -1

Any wrong with my sed command? Thanks !

2 Answers

sed appears to automatically add a newline if the current line was terminated with a newline, and I don't see how to turn that behaviour off.

You might try a different approach: capture the output of the command (the command substitution syntax strips trailing newlines); and then print it without a newline

printf '%s' "$(ls)"

This might work for you (GNU sed):

sed -z 's/\n$//' file
Related