Cannot replace digit with new line in sed but can be replace in sublime

Viewed 114

I have a document with multiple lines. I want to replace the newline characters in the lines that don't end with numbers

Suppose the document is:

line1
line2
line
line
line
line4

I want to get

line1
line2
linelinelineline4

I can do this in sublime by replacing ([^\d])(\n) by \1. While trying this in sed it's not working. Can someone help me what's wrong in this? Thanks in advance

3 Answers

sed doesn't support \d, you can use [0-9] instead. Also, by default, sed works line by line and you cannot manipulate the \n character at end of line. There are ways to overcome this, but I wouldn't suggest to use sed for this task.

$ awk '{ORS = /[0-9]$/ ? RS : ""} 1' ip.txt
line1
line2
linelinelineline4
  • ORS is output record separator
  • /[0-9]$/ check if input line ends with a digit
    • if so, use RS as ORS (which is \n by default)
    • else, use empty string
  • 1 is an awk idiom as a shortcut to print contents of $0 (input record)


perl allows to manipulate newline character as it isn't removed and added back like sed or awk

$ perl -pe 's/(?<!\d)\n//' ip.txt
line1
line2
linelinelineline4

Would you please try the following:

sed '/[^[:digit:]]$/{   ;# if current line ends with non-number
:l                      ;# define a label "l"
N                       ;# read the next line and append to the pattern space
s/\n//                  ;# remove the newline
/[[:digit:]]$/b         ;# if the appended line ends with number, exit the loop
bl                      ;# jump to label "l" and repeat
}' file

This might work for you (GNU sed):

sed ':a;N;/[^0-9]\n/s/\n//;ta;P;D' file

Append the next line and if the first line does not end in a digit, remove the newline and repeat. Otherwise, print/delete the first line and repeat.

Related