【发布时间】:2012-06-05 05:53:25
【问题描述】:
我有一个这样的文件
line1
this is line1
line2
this is line2
line3
this is line3
我想使用 awk 或 sed 来删除每个交替行的尾随换行符,以便像这样合并它们
line1: this is line1
line2: this is line2
line3: this is line3
如何使用 awk 或 sed 进行操作
【问题讨论】:
我有一个这样的文件
line1
this is line1
line2
this is line2
line3
this is line3
我想使用 awk 或 sed 来删除每个交替行的尾随换行符,以便像这样合并它们
line1: this is line1
line2: this is line2
line3: this is line3
如何使用 awk 或 sed 进行操作
【问题讨论】:
$ cat input
line1
this is line1
line2
this is line2
line3
this is line3
$ awk 'NR%2==1 {prev=$0} NR%2==0 {print prev ": " $0} END {if (NR%2==1) {print $0 ":"}}' input
line1: this is line1
line2: this is line2
line3: this is line3
$
【讨论】:
awk 'NR%2==1 {prev=$0} NR%2==0 {print prev ": " $0} END {if (NR%2==1) {print $0 ":"}}' input(顺便说一下,不需要重定向)。
使用sed:
sed -n '${s/$/:/p};N;s/\n/: /p' inputFile
对于带有原始文件备份的就地编辑,
sed -n -i~ '${s/$/:/p};N;s/\n/: /p' inputFile
【讨论】:
sed -n '$p;N;s/\n/: /p' 或 sed -n '${s/$/:/;p};N;s/\n/: /p'
这可能对你有用:
sed -i '$!N;s/\n/: /' file
【讨论】:
sed 's/^\(line.*\)/\1:/' filename | paste - -
还有 Perl 类似物:
perl -ape 's/^(line.+)\n/$1: /' filename
【讨论】: