Dj Destram N
Dj Destram N

Reputation: 25

Merge lines into a huge single line without "spaces" using sed in .txt file

Can't find any solution for this case using sed:

I have .txt files which contain more than 30~ lines in average. I need to merge all the lines into a single huge one without any "spaces" for every file(N amount of files but less than 1000) and paste this line into a new one (1 line for each txt file data). Need this format to parse to .csv table.

Example:

file 1:

    This file 
Contains text 
to merge into
a single line without any
 space between characters 

file 2:

    This file 
Contains almost the same text 
to merge into
a single line without any
 space or blanks between characters after the merge 

file N:

    This file 
Contains equal text 
to merge into
a single line without any
 space between characters 

Output:

This FileContains Textto Merge intoa single line without anyspace between characters
This fileContains almost the same texto merge intoa single line without anyspace or blanks between characters after the merge
This fileContains equal textto merge intoa single line without anyspace between characters

Tried with:

sed -e :a -e '/$/N; s/\n//; ta' test.txt

Didn't work. Text remains the same

Sample Data:

6150217008*AA*31/1*1 
0*4611*1 
349*9171*349*9171*0*0
403*9481*403*9481*0*0
C3*25*
718*17399*718*17399*0*0
C4*25*
794*19293*794*19293*0*0
C5*25*
731*17594*731*17594*0*0
C6*25*

Need to get: 6150217008*AA*31/1*10*4611*1349*9171*349*9171*0*0403*9481*403*9481*0*0C3*2....etc

A huge single raw line text without any spaces.

How can I make that? Thanks!

Upvotes: 1

Views: 2359

Answers (3)

Olli K
Olli K

Reputation: 1760

Here's a bash solution which'll spare the whitespace within the strings but trims leading and tailing whitespace:

#! /bin/bash

for fname in *.txt; do
    while read -r line || [[ -n ${line} ]]; do
        printf "%s" "${line}"
    done < "${fname}"
    printf "\n"
# don't name the result file .txt if it's in the same dir or it'll be included
done > result.dat

This script is assumed to be run in the dir where the txt-files are. You can tweak that part by editing the for-loop

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92884

Simple tr command approach:

tr -d '[:space:]' < test.txt

The output:

6150217008*AA*31/1*10*4611*1349*9171*349*9171*0*0403*9481*403*9481*0*0C3*25*718*17399*718*17399*0*0C4*25*794*19293*794*19293*0*0C5*25*731*17594*731*17594*0*0C6*25*

-d - to delete characters

[:space:] - set of characters representing all horizontal and vertical whitespace

https://linux.die.net/man/1/tr


To redirect the output to a new file use the following:

tr -d '[:space:]' < test.txt > output.txt

Upvotes: 3

Juan Diego Godoy Robles
Juan Diego Godoy Robles

Reputation: 14965

Pretty simple using perl:

perl -pe 's/^\s+|\s*$//g' your_file

Upvotes: 1

Related Questions