Skip to main content

How to Read and Replace Specific Lines in Large Text Files on Linux

🛠️ How to Read and Replace Specific Lines in Large Text Files on Linux

Working with large text files—such as SQL dumps or log files—can be challenging when you're trying to debug or modify specific lines. This guide walks through how to locate a specific line in a file and how to perform in-place string replacements using the Linux command line.

📍 Reading a Specific Line from a File

When dealing with extremely large files (millions of lines), you may need to inspect a specific line to identify syntax errors or incorrect values. For example, to view line 646430 in a file called data_dump_2023.sql, use:

sed -n '646430p' data_dump_2023.sql

🔍 Explanation:

  • sed: A stream editor used for parsing and transforming text.
  • -n: Suppresses automatic printing.
  • '646430p': Prints only line 646430.

For additional context, you can show nearby lines like so:

sed -n '646425,646435p' data_dump_2023.sql

🔄 Replacing a String in a File

If you need to replace a placeholder string (e.g., tempuser123) with something more meaningful like user-1, you can use the sed command:

sed -i 's/tempuser123/user-1/g' data_dump_2023.sql

đź§  Breakdown:

  • -i: Modifies the file in-place.
  • s/tempuser123/user-1/g: Replaces all occurrences of tempuser123 with user-1 in each line of the file.

To preview the change without modifying the file:

sed 's/tempuser123/user-1/g' data_dump_2023.sql | less

And to create a backup before editing:

sed -i.bak 's/tempuser123/user-1/g' data_dump_2023.sql

This creates a backup file named data_dump_2023.sql.bak.

âś… Summary

  • Use sed -n 'LINE_NUMBERp' to read specific lines.
  • Add context with a range like LINE1,LINE2p.
  • Use sed -i 's/old/new/g' to replace text in-place.
  • Always create backups of large or production files before doing destructive edits.

This approach is essential when troubleshooting large data files or performing quick fixes in automated scripts.

Tags