split string to two parts using sed or awk or perl or bash

9,302

Solution 1

echo Grades "ABCDE-12345" | sed 's/-/ /g' | awk '{ print $1" "$2"\n"$1" "$3'}
Grades ABCDE
Grades 12345

or per @steeldriver

awk -F'[ -]' '{print $1, $2; print $1, $3}'

Solution 2

You can do this entirely in your shell, too:

text="Grades ABCDEF-123456"

Split off the leading text. You could capture it if required, but here we'll just discard it:

grades="${text#* }"

Now we could extract the two parts as variables but for now we'll just print them:

echo "Grades ${grades%-*}"
echo "Grades ${grades#*-}"

You can also crash these together into a single output statement, but I don't think it's as readable (even if printf is safer than echo for certain classes of text):

printf "Grades %s\nGrades %s\n" "${grades%-*}" "${grades#*-}"

Solution 3

You can do it by replacing the dash with a newline followed by the first field:

perl -alpe 's/-/\n$F[0] /' 
Share:
9,302

Related videos on Youtube

Sincerity
Author by

Sincerity

Updated on September 18, 2022

Comments

  • Sincerity
    Sincerity over 1 year

    I have string like this:

    Grades ABCDEF-123456
    

    I want to split this string to two sections like this

    Grades ABCDEF
    Grades 123456
    

    How can I do that in bash?

    • don_crissti
      don_crissti over 5 years
      Where does that string come from ? Is it stored in a variable or in a file ? Why tagging this bash if you want (per the title) to use sed, perl or awk ?
    • Sincerity
      Sincerity over 5 years
      i have script for my study and i was unable to figure out how to split strings with the dash - which is pulling the letters and numbers together every time i tried to split it,
  • smw
    smw over 5 years
    There's really no need for sed here - just set the FS to include - i.e. awk -F'[ -]' '{print $1, $2; print $1, $3}'