【问题标题】:replace ending brackets with another string in bash用bash中的另一个字符串替换结束括号
【发布时间】:2021-08-20 13:50:45
【问题描述】:

我想用另一个字符串替换最后 3 行。使用sedtr 或其他bash 解决方案。

给定文件:

{
  [
    {
      text text text
      text text text
      text text text
    }
  ],  
  [
    {
      text text text
      text text text
      text text text
    }
  ]
}

想要的结果:

{
  [
    {
      text text text
      text text text
      text text text
    }
  ],  
  [
    {
      text text text
      text text text
      text text text
bar

我用sed试过这个

sed -i '' 's/\}\s+\]\s+\}/bar/g' foobar.hcl

tr试过这个

tr -s 's/\}[:blank:]\][:blank:]\}/bar/g' <foobar.hcl

【问题讨论】:

  • 你有没有尝试过?如果是这样,请与我们分享。
  • 我调整了描述并添加了我尝试过的内容
  • 请更新问题以显示所需结果
  • @markp-fuso 完成
  • 您要替换的 3 行是否总是文件的最后 3 行? 3行也可以显示在文件的其他地方吗?这 3 行会出现多次吗?

标签: bash sed tr


【解决方案1】:

使用数组 - 假设“text text text”有一些实际的非空格、非标点字符。

mapfile x < file                                # throw into an array
c=${#x[@]}                                      # count the lines
let c--                                         # point c at last index
until [[ "${x[-1]}" =~ [^[:space:][:punct:]] ]] # while last line has no data
do let c--                                      # decrement the last line pointer
   x=( "${x[@]:0:$c}" )                         # reassign array without last line
done
x+=( bar )                                      # add the desired string
echo "${x[@]}" > file                           # write file without unwanted lines

允许任意数量的空行 &c。甚至}]} 之类的,只要它与数据不在同一行。

【讨论】:

    【解决方案2】:

    使用perl,您可以使用-0777 选项将整个输入作为单个字符串读取。如果输入大到足以耗尽可用内存,则不适合。

    # this will replace all remaining whitespaces at the end
    # with a single newline
    perl -0777 -pe 's/\}\s+]\s+\}\s*\z/bar\n/' foobar.hcl
    
    # this will preserve all remaining whitespaces, if any
    perl -0777 -pe 's/\}\s+]\s+\}(?=\s*\z)/bar/' foobar.hcl
    

    一旦工作,您可以使用perl -i -0777 ... 进行就地编辑。

    【讨论】:

    • 这个作品太棒了!我不能投票,因为我没有足够的声誉谢谢!
    【解决方案3】:

    这可能对你有用(GNU sed):

    sed '1N;:a;N;/^\s*}\s*\n\s*]\s*\n}\s*$/{s//bar/;N;ba};P;D' file
    

    打开一个 3 行窗口和模式匹配。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-28
      • 1970-01-01
      • 1970-01-01
      • 2015-04-16
      • 1970-01-01
      • 1970-01-01
      • 2011-08-21
      • 1970-01-01
      相关资源
      最近更新 更多