0

So I have a file with 2 columns as follows:

  10  1
  11  2
  12  3
  13  4
  14  5

I would like to switch the columns using the cut command. I've used

paste <(cut -f2 file.dat) <(cut -f1 file.dat)

And it's giving me the following:

  10  1  10  1
  11  2  11  2
  12  3  12  3
  13  4  13  4
  14  5  14  5

Anyone know how I could use cut and paste to switch the columns? I thought the cut -f1 or cut -f2 would cut each field but apparently not? What am I doing wrong here?

UPDATE: So I'm using -d instead of f and it's giving me weird results and yet when I cat the file, the contents remain unchanged?

  • What is the output of simply cut -f2 file.txt? – Jesse_b Jun 7 '18 at 22:48
  • @Jesse_b it's actually displaying the content of the file as is. I'm confused. My file is also one with .dat extension. But I don't think that changes anything? – CodingNoob Jun 7 '18 at 22:51
2

The default delimiter for cut is a tab character - if you want to cut space-separated data you will need to specify that using the -d argument.

Your input file appears to use multiple spaces which make it harder:

paste <(cut -d' ' -f5 file.txt) <(cut -d' ' -f3 file.txt)
1   10
2   11
3   12
4   13
5   14

or you could replace spaces by tabs (squeezing out repeats) - note that the fields become -f3 and -f2 because your file has leading whitespace:

paste <(tr -s ' ' '\t' < file.txt | cut -f3) <(tr -s ' ' '\t' < file.txt | cut -f2)

In this case, it would be simpler to use awk e.g.

awk '{print $2,$1}' file.txt

or

awk '{print $2,$1}' OFS='\t' file.txt

if you want tab-separated output (as you would get from paste) ex.

$ awk '{print $2,$1}' OFS='\t' file.txt
1   10
2   11
3   12
4   13
5   14
  • It was able to make it work with awk and grep as well, but I also have to do it using cut and paste and I tried the one suggested above and no luck. – CodingNoob Jun 7 '18 at 23:07
  • @CodingNoob you may need to experiment with the field numbers - or count the spaces - if your input is not exactly as you posted (for example, does it really have leading whitespace, as above)? – steeldriver Jun 7 '18 at 23:09
0

So I figured what I wanted to do with the following:

cut -d' ' -f1 file.txt > f1.txt

To cut and append the first column to a new file f1.txt

cut -d' ' -f4 file.txt > f2.txt

To cut and append the second column to a new file f2.txt

paste f2.txt f1.txt > file.txt

And finally to overwrite the original file.txt with switched columns.

  • Then paste <(cut -d' ' -f4 file.txt) <(cut -d' ' -f1 file.txt) should work as well. But note that this approach assumes that every line in your file will have a two-digit number in column 1 and a single-digit number in column 2. – G-Man Jun 8 '18 at 3:32

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.