0

I want to replace a newline with space after a pattern.
For example my text is:
1.
good movie
(2006)
This is a world class movie for music.
Dir:
abc
With:
lan
,
cer
,
cro
Comedy
|
Drama
|
Family
|
Musical
|
Romance
120 mins.

53,097 I want above text to become something like this

1. good movie (2006)
This is a wold class movie fo music.
Dir: abc
With: lan, cer, cro
comedy | Drama | Family | Musical | Romance
120 mins

user2509229
  • 43
  • 1
  • 4

1 Answers1

1

After the question update, the requirements for the solution changed:

cat test.txt | tr '\n' ' '  | perl -ne 's/(?<!\|) ([A-Z])/\n\1/g; print' | sed 's/ ,/,/g' | sed 's/ \([0-9]\+\)/\n\1/g'; echo

output:

1. good movie (2006)
This is a world class movie for music.
Dir: abc
With: lan, cer, cro
Comedy | Drama | Family | Musical | Romance
120 mins. 

Explanation:

  • First I replace all newline characters using tr.
  • Second I replace every capital letter by a preceding newline and itself unless it is preceeded by a pipe "| "symbol.
  • The third one corrects the comma spacings.
  • The last moves the duration declaration to a new line

The echo at the very end is to append a 'newline' to the output.


Deprecated:
Building on kpie's comment, I suggest you the following solution:

cat test.txt | sed ':a;N;$!ba;s/\n//g' | sed 's/\([A-Z]\)/\n\1/g'

I pasted your input into test.txt.
The first sed replacement is explained here: https://stackoverflow.com/a/1252191/1863086
The second one replaces every captial letter by a preceding newline and itself.

EDIT: Another possibility using tr:

cat test.txt | tr -d '\n' | sed 's/\([A-Z]\)/\n\1/g'; echo
Community
  • 1
  • 1
bro
  • 771
  • 3
  • 14
  • This works fine on my ubuntu, but on other machine, it shows as 'Label too long: :a;N;$!ba;s/\n//g' – user2509229 Jul 08 '15 at 00:43
  • what kind of 'other machine'? I tested it on Fedora, Ubuntu and CentOS. Nevertheless, I edited my answer and added another possibility using `tr` instead of `sed` – bro Jul 08 '15 at 06:03
  • well, it is hard to find a working answer when you are changing the requirements.. check the updated answer. – bro Jul 09 '15 at 08:25
  • What if there is a space before | and after this also – user2509229 Jul 17 '15 at 16:34