【问题标题】:Use sed without the need to write on file使用 sed 无需写入文件
【发布时间】:2013-03-16 10:16:09
【问题描述】:

我正在寻找一种绕过文件读写的方法。 是否可以直接在命令结果上使用 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)

【问题讨论】:

  • 您是否尝试重定向命令“disklabel xbd0 | sed -e "s/match1/replace/" \ -e "s/match2/replace/" \ -e "s/match3/ 的结果将/“/file”替换为/file.1?

标签: shell redirect sed command sh


【解决方案1】:

您已经成功地将disklabel 的结果通过管道传输到sed。那么为什么不直接将sed 的结果通过管道传递给 new_command 呢?

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

例如,将 sed 的输出通过管道传输到 sort,然后将其输出通过管道传输到 grep

【讨论】:

  • 是的,它会:只需添加参数(如果您在所有情况下都知道它们并且它们不依赖于磁盘标签或 sed 的输出):disklabel xbd0 | sed -e "s/match/replace/" | new_command arg1 arg2(管道发送 sed 的任何结果将是new_command 的 STDIN。与 new_command 的参数无关)
  • @Stillakid 当然会。你的意思是它需要一个文件参数?这就是/dev/stdin 的用途。
  • @OlivierDulac 是的,我同意,它会将输出发送到 STDIN
【解决方案2】:

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

如果这确实是您的意思,您可以使用xarg 命令来实现:

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

注意xargs 会在空格处打断你的输入,如果你想要一个大参数,你可以使用xargs -0

很可能最好将new_command 设计为从stdin 获取输入,并通过辅助管道传递此输入。

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2016-06-10
      • 2016-07-13
      • 1970-01-01
      • 2016-10-20
      • 2012-10-16
      • 2014-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多