0

I have file consisting of a single line of text. I am trying to obtain the strings between the "#" and "@" symbols and store them as a newline on "Sequence.txt".

For example, I have the input line:

#HelloMyName@#IsAdam@#NiceToMeetYou@

The expected output should be:

HelloMyName
IsAdam
NiceToMeetYou

I have tried the command: following line of code:

sed 's/.*#\(.*\)@.*/\1/' >> Sequence.txt

However, the output is exactly the input:

#HelloMyName@#IsAdam@#NiceToMeetYou@
1

This will work with the gnu version of sed ( by default on every linux )

echo -n '#HelloMyName@#IsAdam@#NiceToMeetYou@' | sed 's/#\([^@]*\)@/\1\n/g'

give me

HelloMyName
IsAdam
NiceToMeetYou

On macos

echo -n '#HelloMyName@#IsAdam@#NiceToMeetYou@' | sed 's/#\([^@]*\)@/\1\'$'\n''/g'

These are examples with echo the same will work files .

echo -n '#HelloMyName@#IsAdam@#NiceToMeetYou@'  > input.txt

sed 's/#\([^@]*\)@/\1\n/g' input.txt > sequence.txt
|improve this answer|||||
0

With GNU awk (gawk), using FPAT to define a field as a sequence of non-#@ characters:

$ gawk '{$1=$1} 1' FPAT='[^#@]+' OFS='\n' file >> Sequence.txt
$ 
$ tail Sequence.txt 
HelloMyName
IsAdam
NiceToMeetYou

Similar approach, in perl:

perl -lpe '$_ = join "\n", /[^#@]+/g' file >> Sequence.txt
|improve this answer|||||
0

This sequence:

[^#]*    # Accept some string of characters that are **not** the start character.
#        # Followed by an start character #
[^@]*    # Followed by an string of **not** ending characters.
@        # Followed by an ending character.

Repeated several times would capture (almost) the whole line.

Like this:

s/[^#]*#\([^@]\)@/\1\n/g

That will convert the input line into several lines as requested.
The only thing missing is to erase what may remain.

sed 's/[^#]*#\([^@]*\)@/\1\n/g;s/\(.*\)\n.*$/\1/'
|improve this answer|||||
0

Assumes that # @ # @.... occur in this order.

$ perl -lne 'print for /#(.*?)@/g' file

Posix Sed:

° turn all @ to newlines, guaranteed to not be present.
° Then shave off upto the leading #.
° Thereby uncovering the element to be printed. 

.

$ sed -e '
   y/@/\n/
   s/^[^#]*#//
   P;D
' file
|improve this answer|||||
  • $ perl -lne 'print for /#(.*?)@/g' file works perfectly, even when there are strings before and after the # and @ respectively, thank you so much! – Gil Ong Oct 7 '19 at 5:34

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.