2

I have a java file in which I have the below line with the CRLF at the end of the Logger.

private static final Logger logger = LoggerCRLF
        .getLogger(MyClass.class);

What I want to do is to remove the CRLF just when it is after Logger in my file and join the line into one line as shown below. This should not affect other CRLFs in my file.

private static final Logger logger = Logger.getLogger(MyClass.class);

I tried the below command to do it

find . -name *.java -exec sed -i 's/Logger\r\n//g' {} \;

but I realized that SED reads one line at a time without trailing newline characters so this is not working. From the man page I was able to find few commands such as N, P and D but I could not make it work.

So the question is how can I remove one CRLF based on the preceding pattern in a file?

Vahid
  • 1,625
  • 1
  • 18
  • 33
  • What about [this answer](https://stackoverflow.com/a/11680914/2877364)? – cxw Jul 11 '17 at 15:37
  • Possible duplicate of [Removing Windows newlines on Linux (sed vs. awk)](https://stackoverflow.com/questions/11680815/removing-windows-newlines-on-linux-sed-vs-awk) – cxw Jul 11 '17 at 15:37
  • @cxw, My question is regarding SED command not TR or VIM text editor. In your example -d of Tr will remove all the tokens – Vahid Jul 11 '17 at 15:43
  • @Vahid can you add expected output for clarity? (for ex: if you want blanks in next line to be removed as well).... also, can you have two consecutive lines ending with `Logger\r\n`? I think this is what you are looking for: `sed '/Logger\r/{N;s/\r\n[[:blank:]]*//}'` – Sundeep Jul 11 '17 at 15:44
  • @Vahid I was looking at the `sed` commands at the bottom of that answer. – cxw Jul 11 '17 at 15:45
  • @sundeep I added the expected result for more clarity. – Vahid Jul 11 '17 at 16:01

3 Answers3

2
$ cat -A ip.txt 
private static final Logger logger = Logger^M$
        .getLogger(MyClass.class);$
$ sed '/Logger\r$/{N;s/\r\n[[:blank:]]*//}' ip.txt | cat -A
private static final Logger logger = Logger.getLogger(MyClass.class);$
  • /Logger\r$/ if line matches this regex
    • N add next line to pattern space
    • s/\r\n[[:blank:]]*// delete CRLF followed by optional blanks
  • This won't work if there are consecutive lines with LoggerCRLF
  • Tested with GNU sed 4.2.2 syntax might vary with other implementations
Sundeep
  • 23,246
  • 2
  • 28
  • 103
0

Right, you've probably realized that to sed, the definition of a "line" is something that ends in a newline, so you're really dealing with multiple lines that you want to join.

You can concatenate lines using the "tr" (translate) command if it is available: How to concatenate multiple lines of output to one line?

drone6502
  • 433
  • 2
  • 7
0
sed '/Logger\r/N;s/\r\s*//' FILE
mop
  • 423
  • 2
  • 11