【问题标题】:sed in bash to overrewrite to same file [duplicate]sed在bash中覆盖到同一个文件[重复]
【发布时间】:2016-04-24 00:10:35
【问题描述】:

我想删除一个文件的标头,并在同一个文件中替换它的内容而没有标头。

示例:file_student

name age
XYS 24
RTF 56

输出应该是:

XYS 24
RTF 56

场景是我不想为此更改创建任何新文件。 sed可以这样做吗?

我试过了:

sed 1d /tmp/file_student.txt |
hadoop fs -copyfromLocal /tmp/file_student.txt /tmp/file_student_no_header.txt

但这不起作用。任何帮助表示赞赏!

【问题讨论】:

  • 感谢@anubhava,但我不想创建备份文件。在这种情况下,它会创建一个 /tmp/file_student.txt.bak 文件
  • sed -i '1d' /tmp/file_student.txt

标签: linux bash shell unix sed


【解决方案1】:

摘自sed 的手册页

-i[SUFFIX]' --in-place[=SUFFIX]' 此选项指定要就地编辑文件。 GNU `sed' 通过创建一个临时文件并将输出发送到 这个文件而不是标准输出。(1)。

 This option implies `-s'.

 When the end of the file is reached, the temporary file is renamed
 to the output file's original name.  The extension, if supplied,
 is used to modify the name of the old file before renaming the
 temporary file, thereby making a backup copy(2)).

 This rule is followed: if the extension doesn't contain a `*',
 then it is appended to the end of the current filename as a
 suffix; if the extension does contain one or more `*' characters,
 then _each_ asterisk is replaced with the current filename.  This
 allows you to add a prefix to the backup file, instead of (or in
 addition to) a suffix, or even to place backup copies of the
 original files into another directory (provided the directory
 already exists).

 If no extension is supplied, the original file is overwritten
 without making a backup.

所以你需要把你的 sed 命令改成 sth like sed -i 1d file | whatever 希望这会有所帮助。

【讨论】:

    【解决方案2】:

    如果您不想使用sed,请尝试tail - 例如你有一个名为 xxx 的文件:

    tail -n +2 xxx > xxx.tmp && mv xxx.tmp xxx

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多