非交互模式编辑文件

非交互模式编辑文件

先理解一下这里的非交互,也就是不需要移动光标。 为什么出现这种需求?

  • 比如写脚本处理文件时。
  • 终端不支持交互模式时。
  • 想一条命令改某个文件的明显位置时。

新建一个作为测试的文本。

echo "foo bar baz" > test.txt

sed http://www.gnu.org/software/sed/manual/

sed -i '' 's/b/B/g' test.txt

awk http://www.gnu.org/software/gawk/manual/

awk '{gsub(/b/,"B")}1' test.txt > test.txt_ && mv test.txt_ test.txt

vi http://vimcdoc.sourceforge.net/doc/help.html

vi -c "%s/b/B/g|wq" test.txt
echo "%s/b/B/g | w" | vim -e test.txt

vi 与 sed 比较

sed 更快。

# Creates 10.000 files to test
for i in {1..1000}; do echo "test" > $i.txt; done

time for i in {1..1000}; do echo "%s/test/new-value/g | w" | vim -e $i.txt; done
# Executes in 22.13s

time for i in {1..1000}; do sed -i '' -e 's/test/new-value/g' $i.txt; done
# Executes in 3.12s

ex 模式

ex -s -c '%s/b/B/g|x' test.txt

perl

perl -i -pe 's/b/B/g' test.txt

参考

https://askubuntu.com/questions/20414/find-and-replace-text-within-a-file-using-commands
https://www.brianstorti.com/vim-as-the-poor-mans-sed/
https://www.brianstorti.com/enough-sed-to-be-useful/
https://sharadchhetri.com/2014/07/06/vi-edit-file-without-opening/

转载于:https://www.cnblogs.com/daysme/p/11133609.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值