4

I need to write a script with the following behaviour:

$ echo $'one&some text\ntwo&other text' | ./my_script.sh --delimiter &
Line:
1st: one
2nd: some tex
Line:
1st: two
2nd: other text

Which can be also called with the default delimiter which is \t:

$ echo $'one\tsome text\nfive\tother text' | ./my_script.sh

Output should be the same as above.

Script should take input via standard in.

What is the easiest way to do this? Possibly in pure bash.

I've tried this approach but it does not work and I don't know why:

while read -r line
do
    echo "$line"
    IFS=$DELIMITER
    arr=(${line//$DELIMITER/ })
    echo ${arr[0]}
    echo ${arr[1]}
done
ragezor
  • 310
  • 4
  • 14

2 Answers2

3

You can do it in bash without using external programs.

$ cat script.sh
#!/bin/bash
if [ "$1" = "--delimiter" ]
then
  d=$2
else 
  d=$'\t'
fi

while IFS="$d" read -r first rest; do
  echo "1st: $first"
  echo "2nd: $rest"
done 
$ echo $'one\tsome text\nfive\tother text' | ./script.sh
1st: one
2nd: some text
1st: five
2nd: other text
$ echo $'one&some text\nfive&other text' | ./script.sh --delimiter \&
1st: one
2nd: some text
1st: five
2nd: other text

Note that the ampersand symbol must be escaped (or quoted) otherwise it will execute the command in the background.

user000001
  • 28,881
  • 12
  • 68
  • 93
2

awk to the rescue...

 echo -e "one&some text\ntwo&other text" | awk 
     `BEGIN {
         n=spit("st,nd,rd,th",s,",")
      } 
      {  print "Line: "; 
         c=split($0,r,"&");  
         for(i=1;i<=c;i++) 
             print i s[(i%10)%n] ": " r[i]
      }

will give

Line: 
1st: one
2nd: some text
Line: 
1st: two
2nd: other text

Note that this simple suffix lookup will breakdown for 11-13

karakfa
  • 62,998
  • 7
  • 34
  • 47