首页 > 解决方案 > 使用 Shell 脚本删除断线

问题描述

我正在尝试从中删除断线:

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

要得到:

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

但我只得到:

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

我正在使用以下代码:tr '\r\n' ' ' < test.txt

标签: bashshell

解决方案


如果输入文件被称为 text.txt 这个命令与 GNU sed 将解决它:

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

bash 输出

说明:

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

您可以在官方文档中阅读更多内容:https ://www.gnu.org/software/sed/manual/sed.html#sed-regular-expressions


推荐阅读