0

Why are the last two array elements being truncated?

I'm trying to generate an array from a string in bash, using a \n as the delaminating character. Using command substitution and tr I was close to what I wanted, now I'm getting strange output.

Script file below

input string: abcd\nefgh\nijkl\nmnop

#!/bin/bash
oper () {
        local fct=$1
        local s=$2
        IFS='\n' read -ra sArr <<< "$s"
        for item in ${sArr[@]}
        do
                printf "   %s\n" $(echo $item | rev)
        done
}
echo "original string: $2"
oper $1 $2
printf "mirror string: "
exit 0

Here's the output

original string: abcd\nefgh\nijkl\nmnop
   dcba
   hgfe
   lkji
   m
   po
1

1 Answer 1

0

Why are the last two array elements being truncated?

Because any character in IFS causes splitting into words, not both. Seeting IFS='\n' splits the input string on \ or n. Because mnop has an n in it, it is splitted to m and op.

First change the sequence of \n character to something that is a single character and uniq - then you may use IFS=.. read. For example:

IFS='!' read -r -a sarr < <(sed 's/\\n/!/g' <<<"$s")

Remember to check you script with http://shellcheck.net to correct quoting problems.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.