Find and Replace a Single Line with sed

sed(1) is the stream editor, documented in the GNU sed manual and the Linux man page. When working with a very large file, the naive sed 's/old/new/' file reads the whole stream — fine for correctness, wasteful when you only need one line. A few addressing tricks make single-line work cheap.

sed -n "${LINE_NUMBER}{p;q}" $FILE
  • -n suppresses default printing; p prints the addressed line; q quits immediately after the first match, so sed never reads the rest of the file.

For a range of lines, q would terminate early, so omit it — and if the file is huge and the range is near the top, just ^C once the output appears:

sed -n "${START_LINE},${END_LINE}p" $FILE

Replace a single line in place

Once the target line number is known:

sed -i "${LINE_NUMBER}s/.*/${REPLACEMENT_TEXT}/" $FILE

.* matches the entire line content at that address, so the substitution rewrites it wholesale. Note that -i on a large file still rewrites the whole file (sed writes to a temp file and renames), and there is no progress indication — you just have to let it finish. Prefer single quotes over double quotes with variable expansion when the replacement text might contain shell metacharacters.

The alternative form, replacing by content match rather than line number, uses the change command: sed -i '/PATTERN/c\Replacement text' $FILE — but that rewrites every matching line unless the address is anchored more precisely.

  • sed -n '=' $FILE prints line numbers; combine with a pattern address (/regex/{=;p}) to locate the line number before editing.
  • For multi-file edits, sed -i lacks backup by default — use -i.bak to keep the original.

Related: findstr (the rough Windows equivalent for searching), find-command.

Sources

See also