Re: delimiters with more than one character? ...
Il 14/07/20 14:52, Albretch Mueller ha scritto:
I have a string delimited by two characters: "\|"
_S=" 34 + 45 \| abc \| 1 2 3 \| c\|123abc "
which then I need to turn into a array looking like:
_S_AR=(
" 34 + 45"
" abc"
" 1 2 3"
" c"
"123abc"
)
I can't make awk or tr work in the way I need and all examples I
have found use only one character.
Is it possible to do such things in bash?
lbrtchx
Hi Albretch,
I would ask why use this type of separators for fields and try to manage
them in bash when one is used for character escaping and the other is
used for piping? If there is not any particular purpose to use them,
change the delimiter characters.
Second question: why do you need 2 separator? Depending on data format
for each field you can choose a valid single delimiter and if your data
format put you in the situation to use multiple character separator you
should use a database (SQlite) and not a simple file.
Over this I'm not a bash guru but this can help:
echo " 34 + 45 \| abc \| 1 2 3 \| c\|123abc " | awk 'BEGIN {FS="|"}
{for(i=1;i<=NF;i++)print $i}' | sed -e 's/\\//g'
I don't know if you need this in a loop (loops in bash are slow) so you
can try this in python.
# python
>>> variable = " 34 + 45 \| abc \| 1 2 3 \| c\|123abc "
>>> list = variable.split("\|")
>>> print(list)
[' 34 + 45 ', ' abc ', ' 1 2 3 ', ' c', '123abc ']
Very simple and efficient (sure you can use perl, C, C++ and other).
My suggestion: when you need to work with files, permission, filesystem
and you need to manage simple string with local tools like awk,sed,tr,
cut....bash is powerfull. When you need to manage a catalog/database
fullfilled by variable type of records then you need a more "advanced"
language, you will gain in performances, flexibility, time in writing
and less problem. Using multiple little program written in another
language (python, C, perl) in your bash script is not so bad. Ah
learning a new language is fantastic.
Hope that helps.
Reply to: