无需 awk 或 sed 的文件就地替换 [英] File inplace replacement without awk or sed

查看:36
本文介绍了无需 awk 或 sed 的文件就地替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,我想用X"替换位置 100-119 之间的任何内容并且我们的 Linux 系统 awk 或 sed 不支持 -i(就地)替换.您能否帮助替代运行一个命令,该命令将有助于替换以D"开头的记录

I have a file in which I would to replace whatever is between position 100-119 with "X" and our Linux system awk or sed doesn't support -i (inplace) replacement. Could you please help with alternative to run a command which will help to replace record which starts with "D"

推荐答案

所有具有就地编辑"功能的命令 cmd选项(awk、sed、perl、ruby 等)在幕后是这样做的:

All any command cmd that has an "inplace editing" option (awk, sed, perl, ruby, etc.) does is this behind the scenes:

tmp=$(mktemp) && cmd 'script' "$file" > "$tmp" && mv -- "$tmp" "$file"

所以你总是可以自己写.

so you can always just write that yourself.

对于任何给定的命令cmd(即sed,或awk,或cut,或tailgrep 或其他任何东西)这里是您创建和调用就地编辑"的方法版本将像具有 -i 类型的就地编辑"选项的工具一样工作;对于多个输入文件:

For any given command cmd (i.e. sed, or awk, or cut, or tail or grep, or anything else) here's how you can create and call an "inplace editing" version that'll work just like the tools that have a -i type of option for "inplace editing" for multiple input files:

cmd_inplace() {
    local tmp file
    tmp=$(mktemp) &&
    for file; do
        cmd 'script' "$file" > "$tmp" &&
        mv -- "$tmp" "$file"
    done
}

cmd_inplace master_file_*

只需将 cmd 替换为您想要调用的任何命令的名称,并将 cmd 'script' 替换为您想要它执行的任何操作.

Just replace cmd with the name of whatever command you want to call and cmd 'script' with whatever you want it to do.

这篇关于无需 awk 或 sed 的文件就地替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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