0

I am completely new to bash and I have a file that contains some string records, let's say

1,2,3,4,5
6,7,8,9,10
11,12,13,14,15

and I need to make another file that looks like this:

2 4 5 3 1
7 9 10 8 6
...

but I got this:

2 4 5
3 1
7 9 10
8 6

The problem is probably caused by the fact that there is no delimiter at the end of the line and it takes enter when printing, but I don't know how to solve this.

#!/bin/bash

FILE=file.txt
a=$(cut -d',' -f2 $FILE)
b=$(cut -d',' -f4 $FILE)
c=$(cut -d',' -f5 $FILE)
d=$(cut -d',' -f3 $FILE)
e=$(cut -d',' -f1 $FILE)


paste <(echo "$a") <(echo "$b") <(echo "$c") <(echo "$d") <(echo "$e") --delimiters ' '> new.txt
beginner17
  • 23
  • 4
  • you should use printf instead of echo https://stackoverflow.com/questions/11193466/echo-without-newline-in-a-shell-script – pinaki Aug 19 '19 at 07:22
  • Also, tangentially, [use lowercase for your private variables](/questions/673055/correct-bash-and-shell-script-variable-capitalization) and [quote them.](/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) – tripleee Aug 19 '19 at 07:27

1 Answers1

5

If your task is simply to change the field separator and reorder the fields, reading the entire file into memory is hugely inefficient. Just process one line at a time.

awk -F, '{ print $2, $4, $5, $3, $1 }' file.txt >new.txt

Awk is more suitable than bare shell script; perhaps see also Bash while read loop extremely slow compared to cat, why?

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Thanks a lot! But I still got enter between fifth and third element. – beginner17 Aug 19 '19 at 07:28
  • 1
    Probably your file contains DOS line endings, too. See https://stackoverflow.com/questions/39527571/are-shell-scripts-sensitive-to-encoding-and-line-endings – tripleee Aug 19 '19 at 07:29
  • With GNU awk. This works with files from Windows or Unix/Linux, if no field contains a carriage return and/or newline: `awk -F, 'BEGIN{RS="\r?\n"} {print $2, $4, $5, $3, $1 }' file` – Cyrus Aug 19 '19 at 11:37
  • Yeah, though not having DOS line endings is probably the way to go if at all possible. I always encourage users to consider getting rid of Windows entirely. – tripleee Aug 19 '19 at 12:21