You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Shell脚本通过参数替换文件中指定行的内容?

Targeted Line Editing with Sed for Your Configuration File

Absolutely! You can make sed only modify the 4th line—no risk of changing other instances of 1000 elsewhere in the file. Here's how to integrate the correct sed command into your existing script:

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

# Robust version: replaces any numeric width value on line 4
sed -i '4s/width: [0-9]*;/width: '"$pixelsize"';/' your_file.txt

Let's break down what this sed command does:

  • 4: This is the line address—it tells sed to only apply the following command to the 4th line of the file.
  • s/old_pattern/new_text/: The substitute command that handles the replacement.
    • width: [0-9]*;: This pattern matches width: followed by any number of digits, then a semicolon. This is more flexible than targeting just "1000" because it works even if you've already changed the width before (so you can run the script multiple times without issues).
    • width: '"$pixelsize"';: This inserts your input pixelsize value in place of the old width, maintaining the correct syntax for your configuration line.

If you strictly want to only replace "1000" (not any existing width) on line 4:

Use this simpler version instead:

sed -i '4s/1000/'"$pixelsize"'/' your_file.txt

Quick note for macOS users:

The -i flag works a bit differently on macOS—you need to add an empty string to avoid creating a backup file by default:

sed -i '' '4s/width: [0-9]*;/width: '"$pixelsize"';/' your_file.txt

Just replace your_file.txt with the actual path to your configuration file, and you're good to go!

内容的提问来源于stack exchange,提问作者D-One

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 03:48:20