0

I have a file which contains lots of records in following manner.

Name
Address
Phone

This is the sequence for each record in that file. Now, I want to copy this file to other file with changed order as below.

Address
Phone
Name

How to write shell script to do this?

  • what is the delimiter between records? – Romeo Ninov May 9 '15 at 14:09
  • They are line by line – shinek May 9 '15 at 14:11
4

Try:

sed -n 'h;n;p;n;G;p' < file.in > file.out

For example:

$ seq 9 | sed -n 'h;n;p;n;G;p'
2
3
1
5
6
4
8
9
7
| improve this answer | |
  • Thanks Stephane. It's working fine for single record in the file, but getting different output than expected if I have multiple records in file. – shinek May 9 '15 at 14:32
  • OK, sorry, see edit. – Stéphane Chazelas May 9 '15 at 14:38
  • It's perfect now. – shinek May 9 '15 at 14:41
  • Terrific! Can you please explain what's going on there (what does the character sequence mean)? – try-catch-finally May 9 '15 at 18:53
  • @try-catch-finally, hold next print next get print – Stéphane Chazelas May 9 '15 at 21:18
2

If I'm reading your question right, you want to take sequences of 3 lines from the file, and swap the order of the first and last in each? With GNU sed, you could do something like this I think:

sed -e :a -e '$!N' -e 's/\(.*\)\n\(.*\)\n\(.*\)$/\2\n\3\n\1/;Ta' file

which continually slurps up lines until it is able to make the swap, and then starts over.

| improve this answer | |
  • @shinek ... well let's wait to see what the sed gurus have to say, I'm sure to have made a boo-boo somewhere ;) – steeldriver May 9 '15 at 14:37
  • You could use first~step to golf it shorter: sed '1~3{h;d};3~3G' – don_crissti May 9 '15 at 17:39
1

With awk:

awk '{l=$0;getline;print;getline;print $0"\n"l;}' < file_in > file_out

Explanation:

  1. Save current record in variable l

  2. Get next record using getline

  3. Print that record (print, invoked without arguments will always print the current record)

  4. Get the next record again using getline

  5. Print that record, a newline and the first record stored in l

  6. For the next record(s) start over at 1.

References

| improve this answer | |

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.