在那之前得到问号和线的行 - sed

时间:2018-03-22 18:29:39

标签: linux bash shell awk sed

我有一些用sed传输的文本(任何其他工具都可以)。我想提取以问号结尾的行和之前的行。我们怎样才能做到这一点?

例如文字

& 434.0K
-

.... 
What are you trying to filter
out of screencap's output?
Student
xcvdgfdg
srrtgg

4 个答案:

答案 0 :(得分:2)

请您试着跟随并告诉我这是否对您有帮助。

package org.maurelio.flipcover;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

/**
 * Created by maurelio on 22/03/18.
*/

public class SensorReceiver extends BroadcastReceiver {
  @Override
  public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, "Intent Detected.", 
    Toast.LENGTH_LONG).show();
  }
}

对于您显示的输入,将是输出。

awk '/\?$/{print prev ORS $0} {prev=$0}'  Input_file

在Solaris / SunOS系统上,将What are you trying to filter out of screencap's output? 更改为awk/usr/xpg4/bin/awk/usr/xpg6/bin/awk

代码说明:

nawk:如果是,请搜索以/\?$/结尾的行,然后执行以下操作。

?:在这里使用{print prev ORS $0}的打印功能,我们在这里打印名为awkprev(当前行)的变量值。

$0:所以我在这里将当前行的值存储到名为prev的变量中,以便在行的最后一行匹配{prev=$0}时,可以打印上一行。

答案 1 :(得分:1)

sed解决方案:

sed -n '/?$/{x;G;p;};h'

粗略翻译:一般情况下,不要打印任何东西。如果此行以'$'结尾,则将其与保留空间中的行前置并打印出来。并将此行保存在保留空间中。

答案 2 :(得分:0)

您可以使用grep来匹配相关行,然后使用-A num表示匹配之后的行或-B num表示匹配前的行。

假设:

$ echo "$txt"
& 434.0K
-

.... 
What are you trying to filter
out of screencap's output?
Student
xcvdgfdg
srrtgg

之前的一行:

$ echo "$txt" | grep -B1 '\?$'
What are you trying to filter
out of screencap's output?

之后的一行:

$ echo "$txt" | grep -A1 '\?$'
out of screencap's output?
Student

支持POSIX和GNU grep。

如果您有多个匹配项,grep会在每个匹配项之间加上--

$ echo "$txt$txt" | grep -A1 '\?$'
out of screencap's output?
Student
--
out of screencap's output?
Student

如果这是一个问题,请通过sed删除它:

$ echo "$txt$txt" | grep  -A1  '\?$' | sed  '/^--*$/d'
out of screencap's output?
Student
out of screencap's output?
Student

答案 3 :(得分:0)

另一种解决方案

sed '$d;N;/?$/!D' infile