Joe Fruchey
Joe Fruchey

Reputation: 409

Mapping lines to columns in *nix

I have a text file that was created when someone pasted from Excel into a text-only email message. There were originally five columns.

Column header 1

Column header 2

...

Column header 5

Row 1, column 1

Row 1, column 2

etc

Some of the data is single-word, some has spaces. What's the best way to get this data into column-formatted text with unix utils?

Edit: I'm looking for the following output:

Column header 1   Column header 2   ...   Column header 5
Row 1 column 1    Row 1 column 2 ...
...

I was able to achieve this output by manually converting the data to CSV in vim by adding a comma to the end of each line, then manually joining each set of 5 lines with J. Then I ran the csv through column -ts, to get the desired output. But there's got to be a better way next time this comes up.

Upvotes: 0

Views: 64

Answers (2)

sgundlach
sgundlach

Reputation: 66

Perhaps a perl-one-liner ain't "the best" way, but it should work:

perl -ne 'BEGIN{$fields_per_line=5; $field_seperator="\t"; \
  $line_break="\n"}                                        \
  chomp;                                                   \
  print $_,                                                \
  $. % $fields_per_row ? $field_seperator : $line_break;   \
  END{print $line_break}'  INFILE > OUTFILE.CSV

Just substitute the "5", "\t" (tabspace), "\n" (newline) as needed.

Upvotes: 1

rawm
rawm

Reputation: 36

You would have to use a script that uses readline and counter. When the program reaches that line you want, use cut command and space as a dilimeter to get the word you want

counter=0
lineNumber=3
while read line
do
 counter += 1
 if lineNumber==counter
   do
      echo $line | cut -d" " -f 4
   done
 fi

Upvotes: 0

Related Questions