使用sed在两个单词之间获取文本

时间:2015-01-14 11:44:48

标签: ruby-on-rails-4 sed

我想找到两个单词之间的文本,这两个单词不在同一行,两个都出现在不同的行上,所以我想找到进来的行(文本行)在单词之间

例如:

example-a, pqr- 411 037.            ] .. abc.

V/s.

xyz abc Transports Ltd.,            ]
517, E, M. G. road,                 ]
hhhh.                               ] ..pqr.

I am doing the testing for example:
example.com

现在我想要一个文本在V/s.之后到...pqr下一行,而..pqr下一行是空行。

我使用了sed -nr '/v[/s]\.*/I{ :loop; n; /\.\.pqr/Iq; p; b loop}' input_file.txt

但它将文本提供给hhhh. ] ..pqr,但我想要下一行,我怎么能用sed命令实现呢?

3 个答案:

答案 0 :(得分:1)

我认为

sed -nr '/V\/s\.*/I { :loop; n; p; /\.\.pqr/I { :loop2; n; p; // b loop2; /^\s*$/ q }; b loop}' foo.txt

是最直接的改编。

那是:

/^V\/s/I {     # starting in a line that starts with v/s
               # (you can go back to your old pattern if my guess about the
               # precise criteria you want here is incorrect)
  :loop
  n            # fetch the next line
  p            # print it
  /\.\.pqr/I { # if it contained ..pqr
    :loop2
    n          # fetch
    p          # and print lines
    // b loop2 # until one does not contain ..pqr (// repeats the previous regex)
               # this inner loop is necessary in case there are two lines
               # containing ..pqr at the end of a section.
    /^\s*$/ q  # and if that line was empty, quit.
  }
  b loop       # loop until then
}

我在开始时更改了模式,因为在我看来v[/s]\.*是猜测的结果,直到正确的事情发生在excample文件中。 v[/s]\.*将匹配v/.vs.v/...vs...,但不匹配v/s. - []表示字符集任何人都可以匹配而不是序列 - [/s]匹配/s

我输入的模式将在一行的开头匹配v/s。或者(取决于您的需求),您可以使用/v\/s/I,它将匹配行中任意位置的v/s,或者/^v\/s\.*$/,它们只匹配完全由{组成的行} {1}}后跟任意数量的句号。

请注意,所有这些都是猜测,因为我不确切地知道文件中某个部分的开头是什么唯一标识。

答案 1 :(得分:0)

sed -n '\#V/s\.#,/\.\.pqr/ {
   \#V/s\.# b
   /\.\.pqr/ n
   p
   }' YourFile

打印V/s.旁边所有部分的所有行,直到第一行pqr...之后的第一行。

答案 2 :(得分:0)

我会像这样使用awk

awk '/V\/s\./ {f=1} /\.\.pqr/ && f {a=1} !NF && a {f=a=0} f' file
V/s.

xyz abc Transports Ltd.,            ]
517, E, M. G. road,                 ]
hhhh.                               ] ..pqr.

这将从找到的Vs.打印到..pqr,下一行为空。

工作原理:

awk '
/V\/s\./ {f=1}          # If "Vs." is found set flag "f"
/\.\.pqr/ && f {a=1}    # If "..pqe" is found and flag "f" is true, set flag "a"
!NF && a {f=a=0}        # If line is blank and "a" is true clear all flags
f                       # If flag "f" is true print the line. 
' file