sed替换变量包含换行符(保留它)

我有一个从网上下载的多行字符串:

toast the lemonade
blend with the lemonade
add one tablespoon of the lemonade
grill the spring onions
add the lemonade
add the raisins to the saucepan
rinse the horseradish sauce

我已将此分配给$INPUT ,如下所示:

INPUT=$(lynx --dump 'http://example.net/recipes' 
     | python -m json.tool 
     | awk '/steps/,/]/' 
     | egrep -v "steps|]" 
     | sed 's/[",]|^ *//g; $d')

此时, $INPUT准备好替换到我的目标文件中,如下所示:

sed -i "0,/OLDINPUT/s//$INPUT/" /home/test_file

当然,sed抱怨没有终止的s命令 - 这是问题所在。

我使用的当前解决方法是在给sed之前echo $INPUT ,但不保留换行符。 echo带换行 - 这是问题。

正确的输出应该保持其换行符。 如何指导sed保存换行符?


hacky的直接答案是用n替换所有换行符,您可以通过添加来完成

| sed ':a $!{N; ba}; s/n/n/g'

到上面的长命令。 更好的答案是,因为将shell变量代入代码通常是一个糟糕的主意,而使用sed则没有选择,而是使用awk代替:

awk -i inplace -v input="$INPUT" 'NR == 1, /OLDINPUT/ { sub(/OLDINPUT/, input) } 1' /home/test_file

这需要GNU awk 4.1.0或更高版本的-i inplace


清理你的代码一些。

这个:

lynx --dump 'http://somesite.net/recipes' | python -m json.tool | awk '/steps/,/]/' | egrep -v "steps|]" | sed 's/"//g' |sed 's/,//g' | sed 's/^ *//g' | sed '$d'

可以用这个替换:

lynx --dump 'http://somesite.net/recipes' | python -m json.tool | awk '/]/ {f=0} f {if (c--) print line} /steps/{f=1} {gsub(/[",]|^ */,"");line=$0}'

它可能会缩短更多,但我现在不这么做: python -m json.tool

这个:

awk '/]/ {f=0} f {if (c--) print line} /steps/{f=1} {gsub(/[",]|^ */,"");line=$0}'

请问:

  • 在模式steps之后打印行以前行] - awk '/steps/,/]/' | egrep -v "steps|]" awk '/steps/,/]/' | egrep -v "steps|]"
  • 中移除了" ,以及在所有的行的前面的所有空间- sed 's/"//g' |sed 's/,//g' | sed 's/^ *//g' sed 's/"//g' |sed 's/,//g' | sed 's/^ *//g'
  • 然后删除该组的最后一行。 - sed '$d'

  • 例:

    cat file
    my data
    steps data
     more
     do not delet this
    hei "you" , more data
    extra line
    here is end ]
    this is good
    

    awk '/]/ {f=0} f {if (c--) print line} /steps/{f=1} {gsub(/[",]|^ */,"");line=$0}' file
    more
    do not delet this
    hei you  more data
    

    假设你的输入JSON片段如下所示:

    { "other": "random stuff",
      "steps": [
        "toast the lemonade",
        "blend with the lemonade",
        "add one tablespoon of the lemonade",
        "grill the spring onions",
        "add the lemonade",
        "add the raisins to the saucepan",
        "rinse the horseradish sauce"
      ],
      "still": "yet more stuff" }
    

    你可以只提取steps成员

    jq -r .steps
    

    要将其插入到sed语句中,您需要在结果中转义任何正则表达式元字符。 一个不太令人生畏的,希望稍微简单一点的解决方案是从标准输入读取静态文本:

    lynx ... | jq ... |
    sed -i -e '/OLDINPUT/{s///; r /dev/stdin' -e '}' /home/test_file
    

    教育从业者为结构化数据使用结构感知工具的努力达到了史诗般的高度,并且一直没有减弱。 在决定使用快速和肮脏的方法之前,至少要确保你了解危险(技术和精神)。

    链接地址: http://www.djcxy.com/p/8277.html

    上一篇: sed substitute variable contains newline (preserve it)

    下一篇: How to log pretty printed json in PHP?