0

Recently, I found this solution, it worked for me because I always used this command with some date and hour, that is, the string almost always unique in my case.

sed -n -i '/some_string_here/,$p' file_here

But recently I needed to use other kind of string (no date and hour)

The problem is, this solution only work from the first ocorrence up

[oracle@server1 ~]$ cat arquivo
OPERATIONAL SYSTEMS:
Windows
MAC OS
OPERATIONAL SYSTEMS TOMORROW:
Linux
Xubunto
OPERATIONAL SYSTEMS TOMORROW:
AIX
SOLARIS

[oracle@server1 ~]$ sed -n -i '/OPERATIONAL SYSTEMS TOMORROW:/,$p' arquivo
[oracle@server1 ~]$ cat arquivo
OPERATIONAL SYSTEMS TOMORROW:
Linux
Xubunto
OPERATIONAL SYSTEMS TOMORROW:
AIX
SOLARIS

I need to do something like this to print from the last occurrence of OPERATIONAL SYSTEMS TOMORROW: until the end.

[oracle@server1 ~]$ cat arquivo
OPERATIONAL SYSTEMS:
Windows
MAC OS
OPERATIONAL SYSTEMS TOMORROW:
Linux
Xubunto
OPERATIONAL SYSTEMS TOMORROW:
AIX
SOLARIS

[oracle@server1 ~]$ sed -n -i 'some command for it' arquivo
[oracle@server1 ~]$ cat arquivo
OPERATIONAL SYSTEMS TOMORROW:
AIX
SOLARIS

How can I do it?

5 Answers 5

2

Here is a one-liner with sed:

sed -n 'H; /^OPERATIONAL SYSTEMS TOMORROW:/h; ${g;p;}' arquivo

Output:

OPERATIONAL SYSTEMS TOMORROW:
AIX
SOLARIS

To edit the file in place:

sed -i -n 'H; /^OPERATIONAL SYSTEMS TOMORROW:/h; ${g;p;}' arquivo
2

Swap the order of the lines in the file, get the first few lines, then swap these again:

$ tac file | sed '/OPERATIONAL SYSTEMS TOMORROW:/q' | tac
OPERATIONAL SYSTEMS TOMORROW:
AIX
SOLARIS

This would possibly not be efficient, but it's simple, and therefore understandable and maintainable.

The tac utility is part of GNU coreutils.

1

You can do this in pure sh using

${VAR%%string}

Where $VAR contains the text you want to process

1

Using aned one-liner:

printf "%s\n" '?^OPERATIONAL SYSTEMS TOMORROW:$?,$w' | ed -s arquivo

or with ex instead:

ex -sc '?^OPERATIONAL SYSTEMS TOMORROW:$?,$wq!' input.txt

these rewrite arquivo to save only everything from the last matching line to the end of the file.

Using a file-oriented tool like ed or ex instead of a stream-oriented one like sed or awk makes many non-trivial automated editing tasks much simpler because they can do things like search backwards from a cursor location.

1

Using perl (maybe faster than awk and sed):

$ cat temp.txt
OPERATIONAL SYSTEMS:
Windows
MAC OS
OPERATIONAL SYSTEMS TOMORROW:
Linux
Xubunto
Extra
OPERATIONAL SYSTEMS:
Windows
MAC OS
OPERATIONAL SYSTEMS TOMORROW:
AIX
SOLARIS  

Execute:

$ perl -ne ' {
  if ( $_ =~ /(OPERATIONAL SYSTEMS TOMORROW:)/ ) {$found=1;$index=0;}
  if($found ) {$index++; $a[$index]=$_;} $last_index=$index;}
  END {
  for($i=1;$i<=$index;$i++){ print $a[$i];}
  } ' temp.txt

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.