繁体   English   中英

使用linux命令替换特定的字符串

[英]specific string replacements using linux commands

我有以下形式的数据:

<some text0>
<text1> <text2> .
<some text1>
<text3> <text4> .

现在,我想将此数据转换为以下形式:

<text1> <text2> <some text0>.
<text3> <text4> <some text1>.

我知道我可以使用C ++做到这一点,但是有一些使用linux做到这一点的方法。 我知道sed擅长替换字符...但是我不知道如何使用sed替换上述形式。

此单线适用于您的示例:

kent$  awk '!/\.$/{s=$0;next}sub(/\.$/,s".")' f
<text1> <text2> <some text0>.
<text3> <text4> <some text1>.

说明:

awk               #the program
!/\.$/{s=$0;next} #if the line was not ending with dot(.),
                  #assign it to s, read next line
sub(/\.$/,s".")   #we are here when the line ends with ".",
                  #then we replace ending "." with s, and print.
f                 #the input file
sed "N;s/\(.*\)\n\(.*\) \.$/\2 \1./" YourFile

sed默认情况下一次将1行读入一个工作缓冲区,并在进程结束时从下一行开始打印内容。

N :向缓冲区添加\\ n,而不是加载输入的下一行

s/Part1/Part2/ :从缓冲区开始直到\\ n,然后\\ n比所有内容都直到。 在end($)之前并以不同的顺序\\ 1 \\ 2分别是第一组和第二组的内容(一组是在s / Part1 / Part2 /的第一部分中的(和)之间找到匹配元素的内容)

注意\\主要用于转义下一个字符,因为“”和。 意思是“点”

通过使用gawk重新定义记录分隔符:

$ awk 'NR>1{print $1,$2,R $3}{R=RT}' RS='<some text[^>]>' file
<text1> <text2> <some text0>.
<text3> <text4> <some text1>.

我会使用awk,但这是一个比较长的管道

sed 's/\.$//' <<END | tac | paste -d " " - - | tac | sed 's/$/./'
<some text0>
<text1> <text2> .
<some text1>
<text3> <text4> .
END    sed 's/\.$//' <<END | tac | paste -d " " - - | tac | sed 's/$/./'
<some text0>
<text1> <text2> .
<some text1>
<text3> <text4> .
END
<text1> <text2>  <some text0>.
<text3> <text4>  <some text1>.

简单易懂的awk

awk '{a=$0;getline;b=$NF;$NF="";print $0 a b}'
<text1> <text2> <some text0>.
<text3> <text4> <some text1>.

a=$0第一行存储在变量a
getline获取下一行b=$NF将最后一个字段存储在b. )中. $NF=""清除最后一个字段print $0 ab打印此行,上一行和b. )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM