我想知道如何使用sed命令完成这项工作:
输入:
http://www.google.com
Google
linktesting
Testing
输出:
Google ; http://www.google.com
Testing ; linktesting
所以在第一行之前的第二行和之间添加了 ;
。
答案 0 :(得分:1)
sed用于单个行上的简单替换,即全部。只需使用其中一个即可获得清晰度,稳健性,可移植性,性能,可维护性以及大多数其他理想的软件标准:
如果没有空行:
$ awk 'NR%2{url=$0;next} {print $0" ; "url}' file
Google ; http://www.google.com
Testing ; linktesting
如果是空行:
$ awk '!NF{next} ++cnt%2{url=$0;next} {print $0" ; "url}' file
Google ; http://www.google.com
Testing ; linktesting
如果您希望输出行之间有空行,请在打印语句中的"\n"
之后添加url
。
答案 1 :(得分:0)
考虑以下两种情况:
案例1:如果输入和输出中确实有空行:
$ cat File
http://www.google.com
Google
linktesting
Testing
然后,您可以执行以下操作:
$ sed 'N;s/\n/ /' File | sed 'N;s/\(.*\)\n\(.*\)/\2 ; \1\n/'
Google ; http://www.google.com
Testing ; linktesting
案例2:如果输入和输出中没有空行:
$ cat File
http://www.google.com
Google
linktesting
Testing
然后,您可以执行以下操作:
$ sed 'N;s/\(.*\)\n\(.*\)/\2 ; \1/' File
Google ; http://www.google.com
Testing ; linktesting
在情况1中,第一个sed
删除空行,而第二个sed
执行反转,将第一行添加到第二行,其中;
。
案例2 sed
只是案例1 sed
的第二部分,但最后没有\n
,因为我们不需要输出中的空行。
答案 2 :(得分:0)
$ sed '/^$/d' File |sed -n 'h;n;p;g;p' | sed 'N;s/\n/ ; /'
Google ; http://www.google.com
Testing ; linktesting
这里先sed:删除空行;第二个sed:每两行旋转一次;第三个:用&#39 ;;'加入每两行。
答案 3 :(得分:0)
如果您的输入和输出文件确实有空行,这样就可以了(GNU sed):
$ sed -r '/^$/d;N;N;s/^(.*)\n\n(.*)$/\2 ; \1/;$!s/$/\n/' infile
Google ; http://www.google.com
Testing ; linktesting
-r
(扩展的正则表达式)是这样的,我不必引用我的括号;其余的工作如下:
/^$/d # Delete empty line; starts new cycle
N # Append empty line to pattern space
N # Append second text line to pattern space
# Rearrange lines, remove empty line
s/^(.*)\n\n(.*)$/\2 ; \1/
$!s/$/\n/ # Append newline, unless we're on the last line
如果我怀疑输入和输出中没有任何空行,这会简化为
$ sed -r 'N;s/^(.*)\n(.*)$/\2 ; \1/' infile
Google ; http://www.google.com
Testing ; linktesting
只需附加下一行并使用替换重新排列两行。