使用sed而无需在文件上写入

时间:2013-03-26 14:51:08

标签: shell redirect sed command sh

我正在寻找绕过文件读写的方法。 是否可以直接在命令结果上使用sed? 使用了#!/bin/sh,因为我使用的是NetBSD,sed -i无效,所以我必须使用sed -e,然后将结果重定向到文件。

命令disklabel xbd0

的结果
netbsd# disklabel xbd0 >/file ;
# /dev/rxbd0d:
type: unknown
disk: xbd0
label: 
flags:
bytes/sector: 512
sectors/track: 2048
tracks/cylinder: 1
sectors/cylinder: 2048
cylinders: 1000
total sectors: 2048000
rpm: 3600
interleave: 1
trackskew: 0
cylinderskew: 0
headswitch: 0           # microseconds
track-to-track seek: 0  # microseconds
drivedata: 0 

16 partitions:
#        size    offset     fstype [fsize bsize cpg/sgs]
 a:   2048000         0     4.2BSD   1024  8192     0  # (Cyl.      0 -    999)
 c:   2048000         0     unused      0     0        # (Cyl.      0 -    999)
 d:   2048000         0     unused      0     0        # (Cyl.      0 -    999)


netbsd# disklabel xbd0 | sed -e "s/match1/replace/" \
-e "s/match2/replace/" \
-e "s/match3/replace/" /file > /file.1 ;

如何在另一个命令中发送结果?

$ new_command -add $(results)

3 个答案:

答案 0 :(得分:3)

您已成功将disklabel的结果汇总到sed。那你为什么不把sed的结果传递给new_command呢?

disklabel xbd0 | sed -e "s/match/replace/" | new_command

例如,将sed的输出传递给sort,然后将其输出传递给grep

答案 1 :(得分:2)

  

如何在另一个命令中发送结果?作为$ new_command -add $(results)

如果这正是您的意思,您可以使用xarg命令实现此目的:

disklabel xbd0 | sed -e "s/match/replace/" | xargs new_command -add

请注意,xargs会破坏您在空格处的输入,如果您想要一个大的参数,则可以使用xargs -0

最有可能最好设计new_command,以便从stdin获取输入并通过补充管道传递此输入。

答案 2 :(得分:0)

在您的代码中,您尝试将命令的输出重定向到/ file,除非您以超级用户身份执行,否则您将获得“权限被拒绝”。 要将一个命令的结果发送到另一个命令,请执行以下操作:

command2 `command1` #if command2 needs output of command1 as an argument

command2 $(command1)  #if command2 needs output of command1 as an argument