使用多个 sed 命令 [英] Using multiple sed commands

查看:78
本文介绍了使用多个 sed 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在搜索文件并输出与以下正则表达式匹配的行的值,但匹配的文本已删除,我不需要将其输出到文件.这是我目前正在使用的,它正在输出所需的文本,但多次:

Hi I'm looking to search through a file and output the values of a line that matches the following regex with the matching text removed, I don't need it output to a file. This is what I am currently using and it is outputting the required text but multiple times:

#!/bin/sh

for file in *; do
sed -e 's/^owner //g;p;!d ; s/^admin //g;p;!d ; s/^loc //g;p;!d ; s/^ser //g;p;!d' $file
done

首选格式是这样的,这样我就可以控制中间发生的事情:

The preferred format would be something like this so I could have control over what happens inbetween:

for file in *; do
    sed 's/^owner //g;p' $file | head -1
    sed 's/^admin //g;p' $file | head -1
    sed '/^loc //g;p' $file | head -1
    sed '/^ser //g;p' $file | head -1
done

示例输入文件如下:

owner sys group
admin guy
loc Q-30934
ser 18r9723
comment noisy fan is something

所需的输出如下:

sys group
guy
Q-30934
18r9723

推荐答案

您多次向 sed 提供 p(用于打印)命令.它每次打印整行.除非你用 -n 选项告诉它不要,sed 无论如何都会在最后打印这一行.

You're giving sed the p (for Print) command several times. It prints the entire line each time. And unless you tell it not to with the -n option, sed will print the line at the end anyway.

您还多次执行 !d 命令.

You also give the !d command multiple times.

在添加多 sed 版本后不要使用 head -q,只需使用 -n 以避免打印不需要的行.或者甚至使用 q (Quit) 在打印您想要的位后停止处理.

Edited after you added the multiple-sed version: instead of using head -q, just use -n to avoid printing lines you don't want. Or even use q (Quit) to stop processing after printing the bit you do want.

例如:

sed -n '/^owner / { s///gp; q; }' $file

{} 将替换和退出命令组合在一起,以便当且仅当模式匹配时才会执行它们.使用了开头地址中的模式后,您可以将其排除在 s 命令之外.所以该命令的缩写是:

The {} group the substitution and quit commands together, so that they are both executed if and only if the pattern is matched. Having used the pattern in the address at the beginning, you can leave it out of the s command. So that command is short for:

sed -n '/^owner / { s/^owner //gp; q; }' $file

这篇关于使用多个 sed 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆