2

I'm looking for a command to add a pattern before or the delimiter.

My sting:

1 |Chris|ubuntu

Here my delimiter is| and I want to generate a string with this input.

Output

1 = ID and Chris = Name and Ubuntu = OS

Sometimes, my input has 2 values only. Let's say 2 | Ram, which has one value and no delimiter, so it should print:

2=ID and Ram=Name

So, field1 + "and" + field2 + "and" + field3. If field3 is not available in the input string then use field1 + "and" + field2.

2
awk -F '|' '
            { printf("%d = ID and %s = Name", $1, $2) } 
    NF == 3 { printf(" and %s = OS", $3) }
            { printf("\n") }' file

This would generate

1 = ID and Chris = Name and ubuntu = OS
2 = ID and  Ram = Name

for the given data. The awk code simply inserts the two first fields into the printf format template. If a third field is available, the OS part is then outputted on the same line. The line is then terminated by a newline.

1

Hi with Miller http://johnkerl.org/miller/doc, starting from this input file

1|Chris|ubuntu 2|Ram

and running

mlr --ifs "|" label ID,Name,OS input.csv

You will have

ID=1,Name=Chris,OS=ubuntu ID=2,Name=Ram

0

In Bash:

#!/usr/bin/env bash

if [ "$#" -eq 0 ]
then
    printf "Missing argument\n" >&2
    exit 1
fi

num_of_delimiters="$(grep -o '|' <<< "$1" | wc -l)"
sting="$(sed -E 's,\s+\|,|,g' <<< "$1")"
sting="$(sed -E 's,\|\s+,|,g' <<< "$sting")"

case "$num_of_delimiters" in
    1)
    echo "$(cut -d '|' -f1 <<< "$sting")"=ID and "$(cut -d '|' -f2 <<< "$sting")"=Name
    ;;
    2)
    echo "$(cut -d '|' -f1 <<< "$sting")" = ID and "$(cut -d '|' -f2 <<< "$sting")" = Name and \
         "$(sed  's/./\U&/' <<< "$(cut -d '|' -f3 <<< "$sting")")" = OS
    ;;
    *)
    printf "More than 2 delimiters or no delimiters\n" >&2
    exit 2
esac

It will also print whitespaces as you showed in your example and will convert the first letter of the third word to uppercase. Examples:

$ ./sting.sh "2 | Ram"
2=ID and Ram=Name
$ ./sting.sh "1 |Chris|ubuntu"
1 = ID and Chris = Name and Ubuntu = OS

No errors reported by https://www.shellcheck.net/.

  • Hey, Im also doing a similar kind of process, But for me the inputs may contains more than 2 delimiters. In this case, how can I remove that restriction? – Bhuvanesh Nov 26 '18 at 20:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.