user9185187
user9185187

Reputation: 52

Shell script: Syntax error: Redirection unexpected:what is the alternate of "<<<" in shell?

Here is my code:

f="\bkg\inp.txt"
while IFS='' read -r line || [[ -n "$line" ]]; do
    IFS='|' read -r -a array <<< "$line"
    #echo "${array[0]}"
    if [ "${array[2]}" == "Sangamithra" ]; then
        printf "%s" "${array[2]}|" "${array[1]}|"${array[0]}"
    fi

done < "$f"

I know what the error is... Since I am new to shell scripting.. I found the code in stackoverflow where we split a string and put into array - But the <<< part is causing problem showing Syntax error : Redirection unexpected.. Now wht should be the replacement for "<<<" in shell script or I have to choose any other way?I am not very much aware of all the syntaxes so could not replace..

Any help is very much appreaciated!!

Upvotes: 1

Views: 9742

Answers (1)

tshiono
tshiono

Reputation: 22062

The alternative for <<< "STRING" is echo "STRING" but if you pipe the output of echo to the read command as echo "$line" | read .., read will be invoked in subshell, in which created variables are not accessible from outside of the subshell. Then please try:

f="\bkg\inp.txt"
while IFS='' read -r line || [[ -n "$line" ]]; do
    IFS='|' read -r -a array < <(echo "$line")
    if [ "${array[2]}" == "Sangamithra" ]; then
        printf "%s" "${array[2]}|${array[1]}|${array[0]}"
    fi
done < "$f"

If you are executing sh, not bash, the script above will also complain about the redirect. Then please consider to switch to bash, or try the following sh compliant version:

#!/bin/sh

f="\bkg\inp.txt"
while IFS='' read -r line || [ -n "$line" ]; do
    IFS="|" set -- $line
    if [ "$3" = "Sangamithra" ]; then
        printf "%s" "$3|$2|$1"
    fi
done < "$f"

Hope this helps.

Upvotes: 2

Related Questions