2009-08-04 50 views
1

解析线延续字符的最简单方法是什么?这似乎是这样一个基本的行动,我很惊讶没有这样做的基本命令。 'while read'和'while read -r'循环没有做我想做的事情,我发现的最简单的解决方案就是下面的sed解决方案。有没有办法做到这一点,像tr一样的基本?解析线延续

 
$ cat input 
Output should be \ 
one line with a '\' character. 
$ while read l; do echo $l; done < input 
Output should be one line with a '' character. 
$ while read -r l; do echo $l; done < input 
Output should be \ 
one line with a '\' character. 
$ sed '/\\$/{N; s/\\\n//;}' input 
Output should be one line with a '\' character. 
$ perl -0777 -pe 's/\\\n//s' input 
Output should be one line with a '\' character. 

+0

请注意,perl解决方案只适用于/ g标志,我甚至不知道如何修改sed来处理多个延续,从而展示这些解决方案的脆弱性。 – 2009-08-04 17:51:24

回答

1

如果“简单”你的意思是简洁和清晰,我建议你的Perl主义与一个小的修改:

$ perl -pe 's/\\\n//' /tmp/line-cont 

不用了,可能是内存密集型... -0777 ...(整个文件slurp模式)开关。

但是,如果通过“简单”你的意思是不是离开外壳,这样就足够了:

$ { while read -r LINE; do 
    printf "%s" "${LINE%\\}"; # strip line-continuation, if any 
    test "${LINE##*\\}" && echo; # emit newline for non-continued lines 
    done; } < /tmp/input 

(我喜欢printf "%s" $USER_INPUTecho $USER_INPUT因为呼应不能可移植被告知停止寻找开关,并且printf通常是内置的。)

只是把它放在用户定义的函数中,不要再被它反叛。警告:后一种方法会在缺少文件的文件中添加尾随换行符。

0

正则表达式的方式看起来像要走的路。

0

我会使用Perl解决方案,因为如果您希望稍后添加更多功能,它可能是最具扩展性的。