Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need to add a space in file

Status
Not open for further replies.

rekim

Programmer
Jul 15, 2003
1
US
Problem: The fields in my flat file are not tab separated. I would like to add tabs (or a space) in between the fields so that it can be processed later.

Here's the catch: The file is large so I do not want to create any intermediary files. So I assume no cutting-pasting – anyway as efficiently as possible.

Bonus points if you can get (read?) each field into a variable for use in a shell script. mrraia@cvs.com


Before:
D02101BOSTON
D05047HARTFORD
D05601WASHINGTON
D22168NEWTON
D02351WATERTOWN

After:
D 02101 BOSTON
D 05047 HARTFORD
D 05601 WASHINGTON
D 22168 NEWTON
D 02351 WATERTOWN
 
Well you can read each line into a shell script, and do some fixed-width field splitting.

Code:
#!/bin/bash

cat c1.txt | ( while read -n 1 code ; do
  read -n 5 area
  read town
  echo "+"${code}"+"${area}"+"${town}"+"
done )

> The file is large so I do not want to create any intermediary files.
I take it you don't want this, if the above works.
 
I think the fastest is the one below with no intermidiary files.

# this is for the 'update'
ex - myFile.txt <<EOF
%s/^\(.\)\(.....\)\(.*\)/\1 \2 \3/g
wq!
EOF

# this is for 'reading':
#!/bin/ksh

sed -e 's/^\(.\)\(.....\)\(.*\)/\1 \2 \3/g' cities.txt | while read code zipcode city
do
echo &quot;code->[${code}] zipcode->[${zipcode}] city->[${city}]&quot;
done;




vlad
+----------------------------+
| #include<disclaimer.h> |
+----------------------------+
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top