Javier Muñoz
Javier Muñoz

Reputation: 780

Removing break lines using Shell Scripting

I'm trying to remove the break lines from this:

Test1,Test2,Test3,Test4
Test1,Test2,Test3,
Test4
Test1,Test2,Test3,Test4
Test1,Test2,Test3,
Test4
Test1,Test2,Test3,Test4

To get:

Test1,Test2,Test3,Test4
Test1,Test2,Test3,Test4
Test1,Test2,Test3,Test4
Test1,Test2,Test3,Test4
Test1,Test2,Test3,Test4

But I'm only getting:

Test1,Test2,Test3,Test4, Test1,Test2,Test3,Test4, Test1,Test2,Test3,Test4, Test1,Test2,Test3,Test4, Test1,Test2,Test3,Test4, Test1,Test2,Test3,Test4

I'm using the following code: tr '\r\n' ' ' < test.txt

Upvotes: 1

Views: 149

Answers (2)

If the input file is called text.txt this command with GNU sed will solve it:

sed 'n;N;s/\n//' text.txt

bash output

The explanation:

n:      # If auto-print is not disabled, print the pattern space, then, 
        # regardless, 
        # replace the pattern space with the next line of input. If there is no 
        # more 
        # input then sed exits without processing any more commands.
        # This command is useful to skip lines (e.g. process every Nth line).

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.

s/\n//  # delete the first newline

You can read more in the official documentation: https://www.gnu.org/software/sed/manual/sed.html#sed-regular-expressions

Upvotes: 4

Ivan
Ivan

Reputation: 7253

Sed variant is good but not obvy even with explanation Take a look at this variant with variable substitution

text=$(cat test)
echo "${text//,$'\n'/,}"

Upvotes: 0

Related Questions