外壳一个衬里以添加到文件中 [英] Shell one liner to prepend to a file

查看:35
本文介绍了外壳一个衬里以添加到文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个复杂的解决方案.

我正在寻找一个简单的运算符,如>>",但用于前置.

恐怕它不存在.我将不得不做类似

<前>mv myfile tmp猫 myheader tmp > 我的文件

还有更聪明的吗?

解决方案

下面的 hack 是一个快速的即兴回答,它有效并获得了很多赞成票.然后,随着这个问题变得越来越流行,而且时间越来越长,愤怒的人们开始报告说它有点奏效,但可能会发生奇怪的事情,或者根本不起作用,所以它一度被强烈反对.好有趣.

该解决方案利用了系统上文件描述符的确切实现,并且由于实现在 nix 之间存在显着差异,因此它的成功完全取决于系统,绝对不可移植,并且不应依赖于任何模糊的重要内容.

>

现在,答案是:

<小时>

为文件创建另一个文件描述符(exec 3<> yourfile)然后写入(>&3)似乎克服了读/写在同一个文件困境.使用 awk 处理 600K 文件对我有用.但是,使用cat"尝试相同的技巧失败了.

将前置词作为变量传递给 awk (-v TEXT="$text") 克服了文字引号问题,这会阻止使用 'sed' 执行此技巧.

#!/bin/bash文字=你好世界这是怎么回事?"执行3你的档案 &&awk -v TEXT="$text" 'BEGIN {print TEXT}{print}' yourfile >&3

This is probably a complex solution.

I am looking for a simple operator like ">>", but for prepending.

I am afraid it does not exist. I'll have to do something like

 mv myfile tmp
 cat myheader tmp > myfile

Anything smarter?

解决方案

The hack below was a quick off-the-cuff answer which worked and received lots of upvotes. Then, as the question became more popular and more time passed, outraged people started reporting that it sorta worked but weird things could happen, or it just didn't work at all, so it was furiously downvoted for a time. Such fun.

The solution exploits the exact implementation of file descriptors on your system and, because implementation varies significantly between nixes, it's success is entirely system dependent, definitively non-portable, and should not be relied upon for anything even vaguely important.

Now, with all that out of the way the answer was:


Creating another file descriptor for the file (exec 3<> yourfile) thence writing to that (>&3) seems to overcome the read/write on same file dilemma. Works for me on 600K files with awk. However trying the same trick using 'cat' fails.

Passing the prependage as a variable to awk (-v TEXT="$text") overcomes the literal quotes problem which prevents doing this trick with 'sed'.

#!/bin/bash
text="Hello world
What's up?"

exec 3<> yourfile && awk -v TEXT="$text" 'BEGIN {print TEXT}{print}' yourfile >&3

这篇关于外壳一个衬里以添加到文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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