Reputation: 1
Here is my code
# text file has: column1:column2:column3:column4:column5:column6:column7
# such as: tang:orange juice
while read line ; do
fields=($(printf "%s" "$line" | cut -d':' --output-delimiter=' ' -f1-))
for i in "${fields[@]}" ; do
echo $i #i also tried echo "$i" but same result
done
done < file.txt
my output would be like:
tang
orange
juice
but it should be like:
tang
orange juice
Upvotes: 0
Views: 62
Reputation: 902
Besides the very short version from @Barmar this would do it in a slightly longer way, which might be more intuitive for a beginner.
while IFS=: read -r -a fields
do
printf "%s\n" "${fields[@]}"
done < file.txt
Upvotes: 0
Reputation: 782755
Use IFS
to specify the field separator for the shell. Then you can split the line using :
as the separator.
IFS=: fields=($line)
Upvotes: 1
Reputation: 882756
Your problem is that you turn the colons into spaces to handle the things as words, not taking into account the fact that some things already have spaces. That means they'll be split into separate words as well.
If your intent is just to take each line of input and place each thing on its own line, you can use something like sed 's/:/\n/g'
as in the following transcript:
pax:~> printf "tang:orange juice:coke\nwater:pale ale\n" | sed 's/:/\n/g'
tang
orange juice
coke
water
pale ale
In your particular case, that would be the relatively simple:
sed 's/:/\n/g' file.txt
Upvotes: 0