使用Shell脚本删除折线

时间:2019-12-31 01:02:57

标签: bash 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

BR, JM。

2 个答案:

答案 0 :(得分:4)

如果输入文件名为text.txt,则使用GNU sed的此命令将解决该问题:

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

bash output

说明:

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

答案 1 :(得分:0)

Sed变体很好,但即使有解释也不会过时 看看这个带有变量替换的变体

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