3

I have 2 directories. SOURCE and DESTINATION. I am moving the .csv files from source to destination as

mv -f SOURCE/*.csv DESTINATION/

While moving, I want to remove the first and last line from each of the file in destination. Please help me with the command.

6

You can't move a file, AND edit it at the same time, since moving a file doesn't physically move the data (on the same filesystem), it just moves a pointer to the data. You can copy and convert the data, then delete the original file, or you can edit the original file, then move it.

cd SOURCE
for i in *.csv
do
 awk 'NR>2{print s} {s=$0}' < "$i" > ../DESTINATION/"${i}"
 rm "${i}"
done

If you omit the rm line, it gives you the opportunity to verify that everything was converted the way you want, before you delete the source files.

  • Now I see that @stany does not want to move the files from SOURCE to DESTINATION, as he says in his question, but wants top copy them, and edit them in the process. In that case, simply remove the rm line from my answer. I decided not to edit my answer, because it answers the question asked. – WormFood Sep 19 '15 at 9:27
  • @terdon, what makes you think that it removes the first 2 lines? That does exactly what the OP asked for. I think you should look at that awk code a little bit closer. I actually tested my code before I posted it here, just to make sure I wasn't overlooking something. – WormFood Sep 19 '15 at 11:28
  • Sorry, I thought I hadn't actually posted that. I'd written it and then realized it was wrong. I blame caching. Anyway, please ignore, deleted now. – terdon Sep 19 '15 at 11:31
3
cd SOURCE
for i in *.csv
do
 sed -i '$d' "$i"
 sed -i '1d' "$i"
 mv "$i" DESTINATION/
done
  • 2
    I usually prefer the syntax: for i in *.csv; do... done ,(rather that ls *.csv) so you do not get bothered if you have some ugly space characters in your file name... – herbert Sep 19 '15 at 8:00
  • does this change the source file? – stany Sep 19 '15 at 8:12
  • @herbert, I'll try your way :) Yes. It will first modify the source and the moved it to destination – SHW Sep 19 '15 at 8:18
  • i dont want to change the source file :( – stany Sep 19 '15 at 8:22
  • @stany you don't want to change file, but want to remove first and last line ? – Archemar Sep 19 '15 at 8: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.