简体   繁体   中英

how to flip columns in reverse order using shell scripting/python

Dear experts i have a small problem where i just want to reverse the columns.For example i have a data sets arranged in 4 columns i need to put last column first, and so on reversely...how can this work be done...i hope some expert will definitely answer my questions.Thanks

in put data example

      1 2 3 4 5
      6 7 8 9 0
      3 4 5 2 1
      5 6 7 2 3

i need output like as below

         5 4 3 2 1
         0 9 8 7 6
         1 2 5 4 3
         3 2 7 6 5 

Perl to the rescue!

perl -lane 'print join " ", reverse @F' < input-file
  • -n reads the file line by line, running the code specified after -e for each line
  • -l removes newlines from input and adds them to output
  • -a splits the input line on whitespace populating the @F array
  • reverse reverses the array
  • join turns a list to a string

What is the type of your data? In python, if your data is a Numpy array then just do data[:, ::-1] . It also work list (but for the first dimension obsviously. In fact it is the general behavior of Python Slice (first, end, stride), where first and last are omitted. It works with any object supported indexing.

But if it is the only data manipulation that you have to do, it may be overkill to use Python to do it. However, it may be more efficient than raw string manipulation (using perl or whatever) depending of the size of your data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM