Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed using a variable for line number restriction

Tags:

bash

sed

I want to do a search and replace on a line with specific line number. However, I want to be able to use a variable for the Line Number itself.

For instance, if I wanted to replace the number 4 with a number 5 on line 180. I would use the following code.

sed '180 s/4/5/' file

My Question is how do I use a variable for the line number?

sed '$variable s/4/5/' file
like image 685
user3591075 Avatar asked Jun 02 '26 21:06

user3591075


2 Answers

@gniourf_gniourf's comment contains the crucial pointer: use double quotes around your sed program in order to reference shell variables (the shell doesn't interpret (expand) single-quoted strings in any way).

Note that sed programs are their own world - they have NO concept of variables, so the only way to use variables is to use a double-quoted string evaluated by the shell containing references to shell variables.

As a result, you must \-escape characters that you want the shell to ignore and pass through to sed to see, notably $ as \$.

In your specific case, however, nothing needs escaping. Thus, as @gniourf_gniourf states in his comment, use:

sed "$variable s/4/5/" file

Afterthought:

Alternatively, the core of your sed program can remain single-quoted, with only the shell-variable references spliced in as double-quoted strings; note that no spaces are allowed between the string components, as the entire expression must evaluate to a single string:

sed "$variable"' s/4/5/' file

While in this specific case you could get away without the double quotes around the variable reference, it's generally safer to use them, so as to avoid unwanted shell expansions (such as word splitting) that could alter or even break the command.

like image 187
mklement0 Avatar answered Jun 05 '26 12:06

mklement0


You could just leave the variable outside of the quotes

sed $variable's/4/5/' file

Note that there cannot be a space between the variable and beginning quote though