Sed Newlines – Fix Sed Failing to Remove Newline Character

newlinessed

I've been using sed for quite some time but here is a quirk I came around with, which I am not able to resolve.

Let me explain my problem with the actual case.


Scene#1

printf "ls" | xclip -selection clipboard
echo "ls" | xclip -selection clipboard

In the first command, I pipe printf output to xclip so that it gets copied to the clipboard. Now, printf, unlike echo does not insert a new line at the end by default. So, if I paste this content into terminal, the ls command that is copied does not automatically run.

In the second, there is a new line at the end, so pasting the clipboard content also results in the running of the command in the clipboard.

This is undesirable for me. So, I wanted to remove the newline using sed, but it failed, as explained in the scene below.

Scene#2

echo "ls" | sed -r 's/\n//g' | xclip -selection clipboard

The content in the clipboard still contains new-line. When I paste it into terminal, the command automatically runs.

I also tried removing carriage return character \r. But nada. It seems I am missing something very crucial/basic here.

Best Answer

sed delimits on \newlines - they are always removed on input and reinserted on output. There is never a \newline character in a sed pattern space which did not occur as a result of an edit you have made. Note: with the exception of GNU sed's -z mode...

Just use tr:

echo ls | tr -d \\n | xclip -selection clipboard

Or, better yet, forget sed altogether:

printf ls | xclip -selection clipboard
Related Question