Home > Software design >  how to use values with sed in shell scripting?
how to use values with sed in shell scripting?

Time:11-28

i am trying te write a shell script in alphametic ,

i have 5 parameters like this

$alphametic 5790813 BEAR RARE ERE RHYME

to get

ABEHMRY -> 5790813

i tried this :

  #!/bin/bash
    echo "$2 $3 $4 $5" | sed  's/ //g ' | sed 's/./&\n/g' | sort -n |  sed '/^$/d' | uniq -i > testing
    paste -sd ''  testing  > testing2 
    sed "s|^\(.*\)$|\1 -> ${1}|" testing2 

but i get error (with the last command sed), i dont know where is the problem .

CodePudding user response:

#!/bin/sh

val="$1"

shift

printf '%s' "$@" | tr '[:lower:]' '[:upper:]' | awk -v FS='' -v OFS='\n' '{$1=$1}1' | sort -n | uniq | tr -d '\n'

printf " -> %s\n" "$val"

edit: Fixed order in output

  • shift removes $1 from the arguments. $@ will then contain all the arguments but the first one, and the old $2 will then be $1, $3 will be $2, etc...
  • printf '%s' "$@" concatenates all the arguments into a single string
  • tr [:lower:] [:upper:] will convert all lower-case letters to their upper-case equivalent.
  • awk -v FS='' -v OFS='\n' '{$1=$1}1' outputs each character vertically
  • tr -d '\n' removes all \n characters

CodePudding user response:

Another approach:

chars=$(printf '%s' "${@:2}" | fold -w1 | sort -u | paste -sd '')
echo "$chars -> $1"

sort's -n does't make sense here: these are letters, not numbers.

CodePudding user response:

One idea using awk for the whole thing:

arg1="$1"
shift
others="$@"

awk -v arg1="${arg1}" -v others="${others}" '
BEGIN { n=split(others,arr,"")                 # split into into array of single characters
        for (i=1;i<=n;i  )                     # loop through indices of arr[] array
            letters[arr[i]]                    # assign characters as indices of letters[] array; eliminates duplicates
        delete letters[" "]                    # delete array index for "<space>"
        PROCINFO["sorted_in"]="@ind_str_asc"   # sort array by index
        for (i in letters)                     # loop through indices
            printf "%s", i                     # print index to stdout
        printf " -> %s\n", arg1                # finish off line with final string
      }
'

NOTE: requires GNU awk for the PROCINFO["sorted_in"] (to sort the indices of the letters[] array)

This generates:

ABEHMRY -> 5790813
  • Related