Mohamed Saligh
Mohamed Saligh

Reputation: 12339

UNIX replace particular line in file

I have file about 5.5GB of size. I want to view a particular line of the file. Lets say line number 100001 and I want to replace that line with my own texts. How to achieve this operation using Unix command. I can not view the file in editor. I can not be opened and that is a remote machine.

Can anyone share some idea to view that line and replacing it with some other texts?

Thanks :)

Upvotes: 0

Views: 1689

Answers (1)

ephemient
ephemient

Reputation: 204668

If you want to modify the line in-place and the replacement data is the same length as the text being replaced, you can use dd to (carefully!) overwrite part of the file.

# getting the byte offsets of the start and length of the line
perl -ne '$s+=length; if ($.==100001) {print "$s + ",length,"\n"; exit}' bigfile

# writing over the existing data
echo 'new line' | dd of=bigfile bs=1 seek=$start count=$length conv=notrunc

If the replacement data is a different length, and it's not at the very end of the file, you have no choice but to rewrite the file. This requires having enough disk space to keep both bigfile and a copy of it!

# The old file is renamed to bigfile.bak; a new bigfile is written with changes.
sed -i.bak -e '100001 c \
new line' bigfile

Upvotes: 1

Related Questions