musicking123
musicking123

Reputation: 3445

how to read each line from a .dat file in unix?

trade.dat is my file which consists of lines of data.

i have to concatanate each line of that file with comma (,)

help me please

Upvotes: 1

Views: 12579

Answers (6)

paxdiablo
paxdiablo

Reputation: 881293

If you mean just add a comma to the end of each line:

sed 's/$/,/' <oldfile >newfile

If you mean join all lines together into one line, separating each with a comma:

awk '{printf "%s,",$0}' <oldfile >newfile

Or the more correct one without a trailing comma (thanks, @hacker, for pointing out the error):

awk 'BEGIN {s=""} {printf "%s%s",s,$0;s=","}' <oldfile >newfile

If you want the output of any of those in a shell variable, simply use the $() construct, such as:

str=$(awk 'BEGIN {s=""} {printf "%s%s",s,$0;s=","}' <oldfile)

I find it preferable to use $() rather than backticks since it allows me to nest commands, something backticks can't do.

Upvotes: 7

William Pursell
William Pursell

Reputation: 212228

perl -pe 's/\n/,/ unless eof'

Upvotes: 1

ire_and_curses
ire_and_curses

Reputation: 70142

Two obligatory perl versions (credit goes to William Pursell for the second one):

perl -i -p -e 'chomp($_); $_ = "$_,\n"' trade.dat

perl -i -p -e 's/$/,/' trade.dat

Note that

  • this does not make backups of the original file by default (use -i.bak for that).
  • this answer appends a comma to every line. To join all lines together into a single line, separated by commas, look at William Purcell's answer.

Upvotes: 2

Vinko Vrsalovic
Vinko Vrsalovic

Reputation: 340191

Answering the question in the title, one way to get each line in a variable in a loop in BASH is to:

cat file.dat | while read line; do echo -n "$line",; done

That will leave a trailing comma, but shows how to read each line.

But clearly a sed or awk or perl solutions are the best suited to the problem described in the body of your question.

Upvotes: 0

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143071

First thing that comes into my head:

gawk -- '{ if(a) { printf ",%s",$0; } else { printf "%s",$0; a=1 } }' trade.dat

if I correctly understand what you want.

Upvotes: 0

Ar3s
Ar3s

Reputation: 2307

try

fullline=""
for line in $(cat trade.dat)
do
         fullline="$fullline,$line"
done
And then use $fullline to show youe file concatenated

hope this'll helps ;p

Upvotes: 1

Related Questions