如果有匹配项,则将文本追加到下一行的开头

时间:2019-12-19 17:15:43

标签: bash unix awk sed grep

我有一个像这样的文件

from a
b
to c
d
from e
f
from g
h
to i
j

如果from匹配,则将to添加到下一行的开头。如果to有一个匹配项,请将from添加到下一行的开头。输出应该是这样

from a
to b
to c
from d
from e
to f
from g
to h
to i
from j

可以使用任何unix命令完成此操作吗?

我尝试粘贴命令以每2行合并,然后使用sed。这样的事情。但这绝对是错误的。另外,我不知道该如何将其再次拆分。

paste -d - - <file> | sed "s/\(^from.*\)/\1 to/" | sed "s/\(^to.*\)/\1 from/"

与正在做的事情相比,我认为应该有一个更简单的解决方案。

4 个答案:

答案 0 :(得分:3)

使用sed

sed '/^from/{n;s/^/to /;b};/^to/{n;s/^/from /}'

您可以try it here

答案 1 :(得分:2)

$ awk '{if ($1 ~ /^(from|to)$/) dir=$1; else $0=(dir=="from" ? "to" : "from") OFS $0} 1' file
from a
to b
to c
from d
from e
to f
from g
to h
to i
from j

答案 2 :(得分:2)

类似的东西应该可以工作:

awk '
    #Before reading the file I build a dictionary that links "from" keywoard to "to" value and inversally
    BEGIN{kw["from"]="to"; kw["to"]="from"}
    #If the first word of the line is a key of my dictionary (to or from), I save the first word in k variable and print the line
    $1 in kw{k=$1;print;next} 
    #Else I add the "opposite" of k at the beginning of the line
    {print kw[k], $0} 
' <input>

答案 3 :(得分:2)

请您尝试以下。

awk '
{
  val=prev=="from" && $0 !~ /to/?"to "$0:prev=="to" && $0 !~/from/?"from "$0:$0
  prev=$1
  $0=val
}
1
'  Input_file