Sed Command behavior difference wrt argument handling

Recently I was working on performing a sed operation on a config file.
I found that the sed command is behaving differently with the parameter -ir vs -ri :-

[root@node system]# sed -ri 's|(^[[:space:]]+[Kk]ernel.*$)|1 transparent_hugepage=never|' temp_file
[root@node system]# echo $?
0

[root@node system]# sed -ir 's|(^[[:space:]]+[Kk]ernel.*$)|1 transparent_hugepage=never|' temp_file
sed: -e expression #1, char 60: invalid reference 1 on `s' command's RHS
[root@node system]# echo $?
1
Asked By: ananTgarg

||

The -i option to sed takes an option argument, a filename suffix to use for the backup file when editing the input file in place. With GNU sed, this option argument is optional, but will obviously be used if supplied.

Using -ir tells sed that the filename of the backup file should have the original name of the input file suffixed by the character r. Since -r is now not used, the back reference in the replacement part of the expression is no longer recognised as a valid, since there is no ( ... ) group in the pattern (which is how you capture a part of a pattern with a basic regular expression).

In conclusion, sed -ri is not the same as sed -ir.

Answered By: Kusalananda
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.