Home > OS >  Printing sequence of strings either using a newlines or without
Printing sequence of strings either using a newlines or without

Time:11-15

I am having a go at printing a sequence of strings, either using a newline between entries. Or printing them next to each other.

Would like to simplify this if I can.

When nwline=1, new lines are used between the printing of arguments. When nwline=0, arguments are printed on same line.

nl determines the number of arguments that get coloured using ctp.

pfm ()
{
    nwline=0
    nl=3
    ctp=$(tput bold)$(tput setaf 39)

    if (( nl >= 1 )); then
      case $nwline in
       1) printf '%s\n' "${ctp}${@:1:nl}${rst}" ;;
       *) printf '%s' "${ctp}${@:1:nl}${rst}" ;;
      esac
      if (( nl   1 <= $# )); then
        case $nwline in
         1) printf '%s\n' "${@:nl 1}" ;;
         *) printf '%s' "${@:nl 1}" ;;
        esac
      fi
    else
      case $nwline in
       1) printf '%s\n' "$@" ;;
       *) printf '%s' "$@" ;;
      esac
    fi
}

Using suggestions I did the following

aggr=("$@")
nk=$((nl-1))

rst=$(tput sgr0) ; ctp=$(tput bold)$(tput setaf 39)

(( nwline == 1 )) && fs=$'\n' || fs=' '
( IFS=$fs ; echo "${ctp}${aggr[*]:0:nk}${rst}" )
(( nl   1 <= $# )) && ( IFS=$fs ; echo "${aggr[*]:nl}" )

But when I use pfm "Mary" "had" "a" "little" "lamb", I get

Mary
had
little
lamb

As observed, I am missing the "a".

CodePudding user response:

Would you please try the following:

pfm ()
{
    local nwline=1
    local nl=3
    local ctp=$(tput bold)$(tput setaf 39)
    local rst=$(tput sgr0)
    local -a ary=("$@")                         # make a copy of arguments
    local fs                                    # field separator: "\n" or ""

    if (( nl > $# )); then nl=$#; fi            # limit the value of nl
    for (( i = 0; i < nl; i   )); do            # highlight the elements indexed lower than nl
        ary[i]="${ctp}${ary[i]}${rst}"
    done

    (( nwline == 1 )) && fs=$'\n' || fs=''      # assign fs to the field separator

    (IFS=$fs; echo "${ary[*]}")                 # execute in subshell not to modify IFS
}

As for the printing of the elements using newline or without, I have used the array variable expansion "${name[*]}" which expands to a concatenation of array elements separated by the first character of IFS.

  • Related