0

I have an array with PIDs in my bash script. I would like to join these with \| as separator as to be able to use grep to search for anything that matches any of the PIDs in the array. I am basically trying to change the IFS as shown below but the problem I encounter is that instead of the desired output:

GREP_ARG='29126\|27435'

I get

GREP_ARG='29126\27435'. 

This is the code I am using

function join {
    local IFS="$1"; shift; echo "$*";
}

GREP_ARG=$(join '\|' "${PID_ARRAY[@]}")

grep -A1 $GREP_ARG file

I have tried to change the input in varius ways but nothing works. Is the IFS approach to this not possible?

0

3 Answers 3

3

You can do

GREP_ARG=$(printf "\|%s" "${PID_ARRAY[@]}")
GREP_ARG=${GREP_ARG:2}
Sign up to request clarification or add additional context in comments.

Comments

1

IFS in BASH supports only single character.

You can use this join function to get any length delimiter:

function join {
   d="$1"
   shift
   arr=("$@")
   last=${arr[${#arr[@]}-1]}
   unset arr[${#arr[@]}-1]
   printf -v str "%s$d" "${arr[@]}"
   printf "%s%s" "$str" "$last"
}

Then call it as:

join '\|' 29126 27435 56789; echo
29126\|27435\|56789

Comments

0
function join {
    echo -n "$2"
    [[ $# -gt 2 ]] && printf "$1%s" "${@:3}"
}

Another version that doesn't need a subshell:

function join {
    VAR=$1 SEP=$2
    local __A=$3 __B
    printf -v __B "${SEP}%s" "${@:4}"
    printf -v "$VAR" '%s' "$__A$__B"
}

join GREP_ARG '\|' "${PID_ARRAY[@]}"

I find it that you'd do eval on those GREP_ARG's. Unless you really know how to safely execute those arguments with eval, the better way would be to use recursive piping functions, but that's already a different context from the topic. You can however refer to a similar topic.

2 Comments

Could do with a bit of explanation.
@TomZych Syntax functions are already explained well in the Bash Manual. Adding more details would be quite helpful yes, but that's still optional. It would also be quite helpful to the Op if he tries to understand it by his own.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.