I need to process a file using a shell script. The file arrives with the data as well as some embedded information releavant to how it is processed.The file is in the following format;email_address system_areaitem_numberitem_numberitem_numberitem_number and so on ...The email_address is required to notify the user submitting the file that it has completed and the system_area indicates to the loading process where the file should be loaded. Therefore I am taking both these values into variables for use in the script.I am currently using 3 sed commands to get the info and then remove the lines;var1=$(sed -n '1p' infile)var2=$(sed -n '2p' infile)sed -i '1,2d' infileThe above code works but I feel it is 'clumsy' and probably inefficient.Does anyone know of a way to achieve the same ends more elegantly/efficiently ?
Copy the first 2 lines from a file and then remove the lines
shell script;text processing;sed
Your code is quite ok, I'd probably do that as a quick solution. It's more efficient to actually exit sed immediately after printing: sed -n '1{p;q}' to avoid reading the entire file for no reason.Now the most awkward part is reading the file twice to get first two lines. You could simply use shell builtins:{ read -r var1; read -r var2; } < infileand then either keep sed -i '1,2d' or simply use tail -n +3 > outfile; mv outfile infile.The ultimate way of doing this in one single pass is to read the two variables with read and then cat the rest:{ read -r var1; read -r var2; cat; } < infile > outfileNote that I'm saving the output into another file (and then you can possibly copy it back). That's not as elegant as inplace modification with sed, but it is safer, and it does the same amount of writing. This last version also only reads the file once, not three times.