I have a 7gb text file
I need to edit n first lines of that file (let us assume n=50)
I want to do this the following way:

head -n 50 myfile >> tmp
vim tmp # make necessary edits
substitute first 50 lines of myfile with the contents of tmp
rm tmp

how do I complete the third step here? better solutions to the general problem are also appreciated note: there is no GUI in this environment


man tail says:

   -n, --lines=[+]NUM
          output the last NUM lines, instead of the last 10;
          or use -n +NUM to output starting with line NUM

therefore you can do

tail -n +51 myfile >>tmp
  • you are right in that the additional result file is redundant. however in comments to another answer we figured out that some systems' implementations of tail command treat the -n argument differently – Alex Agapov Nov 12 '16 at 9:16
  • nevermind that - i forgot about the + modifier which indeed suffers from the 0-fallacy – Alex Agapov Nov 12 '16 at 9:29

Make a backup

cp fileorig.txt fileold.txt

copy 50 lines in tmp.txt

head -n 50 fileorig.txt > tmp.txt

make necessary edits with vim

vim tmp.txt

To make the 3d thing do this

First remove the first 50 lines with sed

sed -i 1,50d fileorig.txt

then cat tmp edited+fileorig.txt in newfile

cat tmp.txt fileorig.txt > filenew.txt

See filenew.txt if you like it if something go wrong restore bacckup

cp fileold.txt fileorig.txt
  • thank you. i'm unsure all the precautions are really necessary, though - copying a 7gb file sounds like a lot. what do you think? – Alex Agapov Nov 12 '16 at 9:05
  • Better wait to copyng than lost forever a file – elbarna Nov 12 '16 at 10:03
  • true. but how exactly can you lose a file this way? – Alex Agapov Nov 12 '16 at 10:18
  • For example a bad command,wrong typing with keyboard,loss of power when file is writed – elbarna Nov 12 '16 at 10:33

found a solution

head -n 50 myfile > tmp
vim tmp # make necessary edits
cat tmp > result
tail -n 50 myfile >> result
# result now contains the edited myfile
  • 1
    you probably need +51 instead of 50 in your tail command. – michas Nov 12 '16 at 9:06
  • no. i just checked it - tail negates first n lines – Alex Agapov Nov 12 '16 at 9:09
  • In that case it probably depends on the tail command provided by your system. At least gnu tail will start with the 50th line. – michas Nov 12 '16 at 9:12
  • interesting, thank you! will keep that in mind – Alex Agapov Nov 12 '16 at 9:13
  • What OS do you work on? What version of tail is installed? (Does tail --version give a hint?) – michas Nov 12 '16 at 9:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.