Reputation: 627
I have a text file with three paragraphs. I want to display the different paragraphs in different colors using bash script commands. Paragraph 1 in red, paragraph 2 in blue and paragraph 3 in cyan.
I managed to display lines in color using commands like
echo -e '\E[32;47m Green.'; tput sgr0
However, I want to parse my file and change colors when there is a new paragraph. I would appreciate for some hints.
Upvotes: 3
Views: 3728
Reputation: 8711
Here's an awk solution, which uses in turn elements of an array of color settings:
BEGIN { nc = split("\33[31;47m \33[34;43m \33[36;40m", colors, " ");
c=1; print colors[c] }
{ print }
/^$/ { c = 1+(c%nc); print colors[c]}
[Edit: The above erroneously adds an extra blank line between paragraphs. Corrected code is as follows:
BEGIN { nc = split("\33[31;47m \33[34;43m \33[36;40m", colors, " ");
c=1; printf "%s", colors[c] }
/^$/ { c = 1+(c%nc); print colors[c]}
!/^$/
The !/^$/
causes any non-blank line to print as is. (End Edit)].
If the above is in file 3-para.awk and data is in file 3-para.data, use a command like awk -f 3-para.awk 3-para.data
to get output like the following.
For more convenient use, define a function that invokes the script and then resets colors to default:
tricolor() {
awk -f 3-para.awk $1; tput sgr0
}
Use the function via (eg) tricolor 3-para.data
Upvotes: 4
Reputation: 185053
The input /tmp/FILE
: http://pastie.org/4928415
The script :
#!/bin/bash
c=1
tput setaf $c
while read a; do
[[ $a =~ ^$ ]] && tput setaf $((++c))
echo "$a"
done < /tmp/FILE
tput sgr0
The output :
Upvotes: 5