Astrid
Astrid

Reputation: 1936

Adding character just to end and beginning of file in shell

I have a bunch of large matrices that I need to reformat, ideally using the shell.

Suppose I have this content stored in example.csv:

1,2,3
2,3,4
5,6,7

Then I do

cat example.csv | tr ',' ' ' | awk '{print "["$0"]"}'

to get

[1 2 3]
[2 3 4]
[5 6 7] 

But I need my final format to look as such

[[1 2 3]
 [2 3 4]
 [5 6 7]]

So how do I accomplish this using the shell with e.g. sed, awk or something similar? I.e. prepending [ to the beginning of the example and appending ] to the last line of the example?

Imagine that my .csv matrices have several thousand columns and rows.

Upvotes: 1

Views: 72

Answers (3)

Jotne
Jotne

Reputation: 41460

Another awk (read the file twice)

awk -F, 'FNR==NR {a=NR;next}
         FNR==1 {$0="["$0} FNR==a {$0=$0"]"}
         {$1=$1;$0="["$0"]";print}' example.csv{,}
[[1 2 3]
[2 3 4]
[5 6 7]]

Upvotes: 2

nu11p01n73R
nu11p01n73R

Reputation: 26667

Just in case you are interested in sed solution

$ sed '1 s/^/[/; s/.*/[&]/; $ s/$/]/; s/,/ /g' input
[[1 2 3]
[2 3 4]
[5 6 7]]

Upvotes: 5

anubhava
anubhava

Reputation: 785791

Just awk can handle this:

awk -F, 'BEGIN{printf "["} NR>1{print ""} {$1=$1; printf "[%s]", $0} 
       END {print "]"}' example.csv
[[1 2 3]
[2 3 4]
[5 6 7]]
  • BEGIN - Print [ without newline
  • -F, Use comma as field separator
  • $1=$1 Change something to tell awk to format output differently using OFS (space by default)
  • NR>{print ""} - Print newline for record # 2 onwards
  • END - Print ] and newline

Upvotes: 4

Related Questions