I have a content file
x a x b x c
I want to see the last case
x c
when i try
sed -n "/x/,/b/p" file
it lists all lines from x to c .
x
c
I'm not sure if I understood your question correctly, so here are a few shots in the dark:
Print the last occurrence of x (regular expression):
grep x file | tail -1
As an alternative:
tac file | grep -m1 x
Print the file from the first line to the end:
awk '/x/{flag = 1}; flag' file
Print the file from the last corresponding line to the end (prints all lines in case of discrepancy):
tac file | awk '!flag; /x/{flag = 1};' | tac
This may work for you (GNU sed):
sed '/x/h;//!H;$!d;x' file
Saves the last x and what follows on hold, and prints it at the end of the file.
not sure how to do this using sed , but you can try awk
sed
awk
awk '{a=a"\n"$0; if ($0 == "x"){ a=$0}} END{print a}' file
grep -A 1 x file | tail -n 2
-A 1 tells grep to print one line after the match stringwith tail you get the last two lines.
-A 1
tail
or in reverse order:
tac fail | grep -B 1 x -m1 | tac
Note: you must ensure that your pattern is strong enough so that you get the correct lines. that is, enclosing it in ^ at the beginning and $ at the end.
^
$