Python Forum

Full Version: Python equivalent to sed [solved]
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm trying to create a program guide for BBC Radio 4 Extra.
I'm using python3.4 and Debian linux on Raspberry Pi

In linux the stream editor (sed) can extract content using

sed -n '/14:00/, +3p' mon

which will extract from program guide (mon) at time 14:00 and display
next 3 lines +3p

In python3 I've redirected stdout to a variable called 'content' which works
but cannot find a way to make the time a variable. Code used

insert os

content = os.popen("sed -n '/14:00/, +3p' mon").read()
This gives the same results and content gets the value of stdout.
However if I wanted to change time (14:00) I cannot pass this as a variable

e.g.
time ="14:00"
content = os.popen("sed -n '/time/, +3p' mon").read()

fails to extract any content.

There is possibly more than one way to do this, and there may be some function
in the python standard library.
I can't find a way to attach the file called 'mon'
Truncated content below:


Output:
14:00 Book at Bedtime—James Bond - Solo, Episode 6 6/10 His mission in Dahum violently interrupted, Bond goes home to plan revenge. 7. 14:15 The Making of Music—Series 1, Bach's St Matthew Passion 16/30 Johann Sebastian's recurring choral theme had a profound effect on the history of music. 8. 14:30 Maggie Allen - Not Me, But Us—Beginnings 1/10 The story of a medical pioneer who campaigned for women's education in the 19th century. 9.
Thanks in advance.
(Sep-24-2018, 02:32 PM)cygnus_X1 Wrote: [ -> ]time ="14:00"
content = os.popen("sed -n '/time/, +3p' mon").read()


It would be a crazy world indeed, if all your variables were just injected into strings. You need to specifically let python know in some way that you expect interpolation to be taking place:
>>> time = "14:00"
>>> "spam /time/ eggs"
'spam /time/ eggs'
>>> "spam /{0}/ eggs".format(time)
'spam /14:00/ eggs'
>>> f"spam /{time}/ eggs"
'spam /14:00/ eggs'
Thanks for your reply Nilamo, I see my mistake now.

content = os.popen("sed -n '/time/, +3p' mon").read()

The solution I used was string concatenation:

str1 = "sed -n '/" + str(time)+ "/, +3p' mon"

content = os.popen(str1).read()
It may not be the best or indeed the only solution but it
works for my purpose.