如何用带有shell脚本的参数替换文件中的特定行?

时间:2018-05-16 00:55:17

标签: bash shell unix sed

我想使用可配置的参数替换文本文档中的特定行。文本文档示例:

DialogUpdateTags,
DialogProductNotFound
{
    width:                          1000;
    height:                         166;
}

在上面的示例中,我想编辑第4行" 1000"特别是这样脚本不会编辑其他可能也是1000的宽度值。到目前为止我有这个:

echo "Enter the desired width size in pixels"
read pixelsize
echo "Width size will be $pixelsize"

之后我需要一个sed命令,任何人都可以帮忙吗? 有没有办法只将SEP指向第4行而不编辑其他内容?

2 个答案:

答案 0 :(得分:1)

使用GNU sed:

pixelsize="30"
sed -E "4s/(width: *)[^;]*/\1$pixelsize/" file

输出:

DialogUpdateTags,
DialogProductNotFound
{
    width:                          30;
    height:                         166;
}

如果你想编辑你的文件"就地"使用sed的选项-i

答案 1 :(得分:1)

width="30"
path=textfile.txt
sed -i "4s/1000;/$width;/" "$path"
相关问题