Reputation: 37
I have been trying to print two lines from the csv file to print horizontally and loop the next two lines and try to do the same.
The code which I have tried is
while IFS=, read -r name code;
do
echo "$name" "$code" | head -2 | tr ' '
done < csvfile.csv
The csv file contains
Albany, N.Y
Albuquerque, N.M.
Anchorage, Alaska
Asheville, N.C.
Atlanta, Ga.
Atlantic City, N.J.
All I want is the output like
Albany, N.Y. Albuquerque, N.M.
Anchorage. Alaska.
Asheville, N.C. Atlanta, Ga.
and so on
Can anyone help me with this. I have tried different ways as suggested online but still no luck and am a newbie in bash scripting. Any help would really be appreciated. Thank you
Upvotes: 0
Views: 165
Reputation: 7831
With pr(1)
pr -ta2 file.csv
If ed(1)
is available/acceptable.
printf '%s\n' ',s/$/ /' 'g/./j' ',s/ $//' ,p Q | ed -s file.csv
Upvotes: 0
Reputation: 204064
You subject says "loop 3 lines" but the text in your question says "loop 2 lines" and it's not clear what the formula would be to get the output you say you want from the input you posted so... is this what you're trying to do?
$ paste - - < csvfile.csv
Albany, N.Y Albuquerque, N.M.
Anchorage, Alaska Asheville, N.C.
Atlanta, Ga. Atlantic City, N.J.
or if you prefer:
$ awk -v OFS='\t' 'NR%2{p=$0; next} {print p, $0}' csvfile.csv
Albany, N.Y Albuquerque, N.M.
Anchorage, Alaska Asheville, N.C.
Atlanta, Ga. Atlantic City, N.J.
It's trivial control whether a tab or blank or any other delimiter appears between columns with either command of course.
See why-is-using-a-shell-loop-to-process-text-considered-bad-practice
Upvotes: 1