【问题标题】:Sed in place replacement given a range of location给定一系列位置的 sed 就地替换
【发布时间】:2018-11-25 13:41:35
【问题描述】:

我有一个类似的文本文件

Firstline
Sometext1 randomtext1
Sometext2 randomtext2
Sometext3 randomtext3
Sometext4 randomtext4
.
.
.
lastline

预期输出

Firstline
Sometext1 commontext
Sometext2 commontext
Sometext3 commontext
Sometext4 commontext
.
.
.
lastline

不包括第一行和最后一行,对于位置范围(如位置 10 到位置 20)的所有行,我在此范围内有要替换的通用文本

如何使用 sed 就地替换来实现这一点?

目前我正在将除第一行和最后一行之外的所有行放入一个文件中,在这个文件上我正在运行 awk gsub(start location, offset) 我将文件名作为参数传递给脚本

cp $1 $1_original
sed '1d;$d' $1 > output_interim.txt;
awk '{gsub (substr($0,10,10),"commontext",$0); print $0 }' output_interim.txt > output.txt;
(head -1 $1_original; cat output.txt; tail -1 $1_original) > $1;

【问题讨论】:

  • 你在这个问题上做了哪些努力?看看Minimal, Complete, and Verifiable example
  • 嗨阿德里安,目前我正在将除第一行和最后一行之外的所有行放入一个文件中,在这个文件上我正在运行 awk gsub(start location, offset) ,这会产生额外的创建/删除临时的开销文件
  • 那么请使用您现有的解决方案更新您的问题。它可以帮助其他人弄清楚您到底想要实现什么以及您遇到了什么问题。如果您的问题是创建中间文件对空间或性能的影响,那么是否有使用管道的解决方案?
  • 请将该示例输入的所需输出添加到您的问题中。

标签: string sed replace


【解决方案1】:

假设 GNU sed(对于 -r 选项)

在这里,我将“location11”替换为“location17”,并使用文本“common”——保存前 10 个字符并替换接下来的 6 个字符:

sed -r '1n; $n; s/^(.{10}).{6}/\1common/' <<END
Firstline
Sometext1 randomtext1
Sometext2 randomtext2
Sometext3 randomtext3
Sometext4 randomtext4
.
.
.
lastline
END
Firstline
Sometext1 commontext1
Sometext2 commontext2
Sometext3 commontext3
Sometext4 commontext4
.
.
.
lastline

然后,要使用备份副本就地写入,请将-i.bak 选项添加到 sed。

【讨论】:

  • 嗨格伦,谢谢,我的字符串不限,让我说清楚,在从开始位置到结束位置的每一行中,我必须用一个通用字符串替换
  • 还是不清楚。什么是“开始位置”和“结束位置”?请编辑您的问题以提供详细信息。此外,提供所需的输出。
  • 目前我正在将除第一行和最后一行之外的所有行放入一个文件中,在这个文件上我正在运行 awk gsub(start location, offset) ,这有创建/删除临时文件的额外开销,关于位置 10 到位置 20 ,位置是正确的单词,在 abcde 中,位置 2 到位置 5 将是 'bcd'
猜你喜欢
  • 2019-10-13
  • 2017-01-06
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 2013-11-11
  • 1970-01-01
  • 2011-08-12
  • 1970-01-01
相关资源
最近更新 更多