使用.txt文件中的sed将行合并为一条没有“空格”的巨大单行

时间:2017-04-04 12:13:42

标签: bash sed merge

使用sed找不到任何解决方案:

我的.txt文件平均包含超过30行。 我需要将所有行合并为一个巨大的行,每个文件没有任何“空格”(N个文件但少于1000个)并将此行粘贴到一个新行(每个txt文件数据为1行)。需要这种格式来解析.csv表。

示例:

文件1:

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

文件2:

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

文件N:

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

输出:

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

试过:

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

没用。文字保持不变

示例数据:

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*

需要得到: 6150217008 * AA *一分之三十一* 10 * 4611 * 1349 * 9171 * 349 * 9171 * 0 * * 0403 9481 * 403 * 9481 * 0 * 0C3 * 2 ....等

没有任何空格的巨大单行原始文本。

我该怎么做?谢谢!

3 个答案:

答案 0 :(得分:0)

简单 tr 命令方法:

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

输出:

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 - 删除字符

[:space:] - 表示所有水平和垂直空白的字符集

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

要将输出重定向到新文件,请使用以下命令:

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

答案 1 :(得分:0)

使用perl非常简单:

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

答案 2 :(得分:0)

这是一个bash解决方案,它会在字符串中保留空格,但会修剪前导和尾随空格:

#! /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

假设此脚本在txt文件所在的目录中运行。您可以通过编辑for - 循环

来调整该部分