简体   繁体   中英

How do I split a number of words on delimiter in sed or with awk

Remark: soultion must be only with sed or awk

I have the following line: ( example from file )

     jn34r 38&Y EY$@H #EY$@HDCmhf453gf=,e73e3bnd2wbyzd fr fr4fn3r f 4df 3

in the following example we see that:

Before "=" delimiter we have the words

  jn34r 38&Y EY$@H #EY$@HDCmhf453gf

And after the "=" delimiter we have the words

,e73e3bnd2wbyzd fr fr4fn3r f 4df 3

so now I want to split the words before delimiter and the words after delimiter by sed ( I write a sed syntax - but this sed command give me partial solution ,

EXAMPLE:

        echo "jn34r 38&Y EY$@H #EY$@HDCmhf453gf=,e73e3bnd2wbyzd fr fr4fn3r f 4df 3" | sed "s .*\(=\) \1 "  | sed s'/=//g'

I get the following results

,e73e3bnd2wbyzd fr fr4fn3r f 4df 3

as all know sed give me the words after delimiter

what I want to get is the words before delimiter and after

please advice what I need to my sed syntax in order to get the words before and after delimiter ,

solution should be like this

 words_before=jn34r 38&Y EY$@H #EY$@HDCmhf453gf
 words_after=,e73e3bnd2wbyzd fr fr4fn3r f 4df 3

Try this:

echo <source> | sed "s/\(.*\)=/words_before=\1\nwords_after=/" 

Test code:

echo "n34r 38&Y EY$@H #EY$@HDCmhf453gf=,e73e3bnd2wbyzd fr fr4fn3r f 4df 3" \
  | sed "s/\(.*\)=/words_before=\1\nwords_after=/" 

Output:

words_before=n34r 38&Y EYH #EYHDCmhf453gf
words_after=,e73e3bnd2wbyzd fr fr4fn3r f 4df 3

Would this do what you want?

$ awk -F= '{printf "%s\n%s\n", $1, $2}' x
jn34r 38&Y EY$@H #EY$@HDCmhf453gf
,e73e3bnd2wbyzd fr fr4fn3r f 4df 3

This is easily modified to provide leading and/or trailing text (that could even be different for the part before and after the = delimiter).

awk中 ,可以使用-F选项设置分隔符:

echo "jn34r 38&Y EY$@H #EY$@HDCmhf453gf=,e73e3bnd2wbyzd fr fr4fn3r f 4df 3" | awk -F= '{print "words_before="$1"\nwords_after="$2}'

There are a lot of ways to do this. It really depends on what your goals are. Does this work for you?

$ echo "asdf asdf asdf asdf  = geitgm gao dbageiobna eb" | sed "s/=/\n/"
asdf asdf asdf asdf  
 geitgm gao dbageiobna eb

This works with and without spaces:

$ echo "asdfa asdf asd fasd f=sfsafd asdf asd fasdf " | sed 's/=/\n/'
asdfa asdf asd fasd f
sfsafd asdf asd fasdf 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM