Tag Info

New answers tagged

3

There are all kinds of reasons why reading a whole file into pattern space can go wrong. The logic problem in the question surrounding the last line is a common one. It is related to sed's line cycle - when there are no more lines and sed encounters EOF it is through - it quits processing. And so if you are on the last line and you instruct sed to get ...


5

It fails because the N command comes before the pattern match $! (not last line) and sed quits before doing any work: N Add a newline to the pattern space, then append the next line of input to the pattern space. If there is no more input then sed exits without processing any more commands. This can be easily fixed to work with single-line input ...


2

If you are just putting commands in the clipboard echo -n "ls " | xclip -selection clipboard If you additionally need to make more complex transformations, echo "ls " | perl -pe 's/\n//' | xclip -selection clipboard


3

Many text processing tools, including sed, operate on the content of the line, excluding the newline character. The first thing sed does when processing a line is to strip off the newline at the end, then it executes the commands in the script, and it adds a final newline when printing out. So you won't be able to remove the newline with sed. To remove all ...


6

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: ...


3

The pattern argument to grep is in fact a newline-separated list of patterns. Thus grep $'\r\n' searches either a CR or the empty pattern (which matches every line). This is the same as grep $'\n' which searches the empty pattern or the empty pattern. To search for a CRLF sequence, search for a CR at the end of the line. grep -c $'\r$' file


1

I tend to reach for perl one-liners when doing anything that involves manipulating line endings: perl -pe 'BEGIN {undef $/} s/\r\n//g' *.txt The key to making this work is the undef $/, which makes Perl read each file as one string, which you can then do a search-and-replace on. To strip bare \r as well, just tweak the regex: perl -pe 'BEGIN {undef $/} ...


5

sed ":a;/\r$/{N;s/\r\n//;b a}" This will match all lines that have '\r' at the end (followed by '\n'). On these lines it will first append the next line of input (while putting the '\n separator in between), then replace the resulting "\r\n" with an empty string, and then goes back to the beginning to see, whether the new contents of pattern space doesn't ...



Top 50 recent answers are included