D-One
D-One

Reputation: 3

How to replace a specific line in a file with an argument with shell script?

I would like to replace a specific line in a text document using a configurable argument. Text document example:

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

In the example above I want to edit line 4 "1000" specifically so the script doesn't edit other width values that might also be 1000. So far I have this:

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

After that I need a sed command, can anyone help? Is there a way to point SEP only to line 4 and not edit anything else?

Upvotes: 0

Views: 1251

Answers (2)

akash
akash

Reputation: 793

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

Upvotes: 1

Cyrus
Cyrus

Reputation: 88636

With GNU sed:

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

Output:

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

If you want to edit your file "in place" use sed's option -i.

Upvotes: 2

Related Questions