Programmatically build string for printf

Jezen Thomas

I’m trying to build up a colourful line to be printed to my terminal.

I’m writing my message to a file with Ruby.

def warn(line)
  log = File.open("#{File.dirname(__FILE__)}/../../log/import/import.log", "a")
  log.puts("WARN #{line}")
  log.close
end

A typical line written to the log file will look like this:

WARN Client insertion failed: [149] Validation failed: Email is invalid

I’m continuously reading from this file with tail:

tail -F -n 0 log/import/import.log | script/report.sh

The script I’m piping the tail output to looks like this:

#!/bin/bash

set -e

while read LINE; do
  case "$LINE" in
    "file truncated")
      clear
      ;;
    INFO*)
      tput setaf 6
      echo "${LINE:5}"
      tput sgr0
      ;;
    WARN*)
      tput setaf 1
      printf "${LINE:5}" | cut -d ":" -f1
      tput sgr0
      printf ": "
      tput setaf 3
      printf "["
      tput sgr0
      printf "${LINE:5}" | cut -d "[" -f2 | cut -d "]" -f1
      tput setaf 3
      printf "]"
      tput sgr0
      printf "${LINE:5}" | cut -d "]" -f2
      printf "\n"
      ;;
    *)
      echo "$LINE"
      ;;
  esac
done

My output is being printed onto separate lines, so it looks like this:

Current terminal output

However, I’d like each error to be printed on its own line, like this:

desired output

How can I make this work?


After receiving some excellent answers, I refactored my script to look like this:

#!/bin/bash

set -e

printfg() {
  tput setaf $3
  printf "$1" "$2"
  tput sgr0
}

while read LINE; do
  case "$LINE" in
    "file truncated")
      clear
      ;;
    INFO*)
      printfg "%s\n" "${LINE:5}" 6
      ;;
    WARN*)
      IFS="[]" read error number reason <<< "$(echo "${LINE:5}")"
      printfg "%s" "$error" 1
      printfg "%s" "[" 3
      printf "%s" "$number"
      printfg "%s" "]" 3
      printf "%s\n" "$reason"
      ;;
    *)
      echo "$LINE"
      ;;
  esac
done
nu11p01n73R

The problem is that the cut command outputs a newline \n character at the end of the output.

One way to overcome this is to use some command substitution technique

for example

$printf "hello world" | cut -f1
hello world
$

can be modified as

output=`printf "hello world" | cut -f1`
printf $output
hello world$

see the bash prompt $ at the end of output hello world

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related