In the below shell script I want to extract the fields of a string delimited by |
character. But unfortunately I'm facing issue if there exists pipe command |
in the string, because of which I'm not able to extract the required fields
#!/bin/bash
_a=""
b=""
_c=""
_d=""
test_def1="abc|pidof abc|0|0"
if [[ "$test_def1" == *"|"*"|"*"|"* ]]; then
echo "valid"
IFS='|' read -r _a b _c _d <<< "${test_def1}"
readarray -t _process_ids < <(ssh -o StrictHostKeyChecking=no -l root 192.168.1.50 "$b")
else
echo "invalid"
fi
test_def2="abc|ps -a | awk "/abc/ { print \$1 }"|0|0"
if [[ "$test_def2" == *"|"*"|"*"|"* ]]; then
echo "valid"
IFS='|' read -r _a b _c _d <<< "${test_def2}"
# expecting b to contain ps -a | awk "/abc/ { print \$1 }"
readarray -t _process_ids < <(ssh -o StrictHostKeyChecking=no -l root 192.168.1.50 "$b")
else
echo "invalid"
fi
Current output
valid
pidof abc
main.bash: line 18: {: command not found
invalid
Expected output
valid
pidof abc
valid
ps -a | awk "/abc/ { print \$1 }"
test_def2="abc|ps -a | awk "/abc/ { print \$1 }"|0|0"
, and especially how it looks like with the syntax highlighting above.ps -a | awk "/abc/ { print \$1 }"
syntax messing up with the pattern that I'm trying to match. Even if I maketest_def2
asabc|ps -a | awk '/abc/ { print \$1 }'|0|0
, it's matchingb
withps -a
instead ofps -a | awk '/abc/ { print \$1 }'
|
characters, you can solve the problem by extracting fixed fields from the beginning and end, and then everything in between is the more general field.