Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python equivalent to sed

Tags:

Is there a way, without a double loop to accomplish what the following sed command does

Input:

Time Banana spinach turkey 

sed -i "/Banana/ s/$/Toothpaste/" file

Output:

Time BananaToothpaste spinach turkey 

What I have so far is a double list which would take a long time to go through both.

List a has a bunch of numbers list b has a the same bunch of numbers but in a different order

For each entry in A i want to find the line in B with that same number and add value C to the end of it.

Hope this makes sense, even if my example doesn't.

I was doing the following in Bash and it was working however it was super slow...

for line in $(cat DATSRCLN.txt.utf8); do         srch=$(echo $line | awk -F'^' '{print $1}');         rep=$(echo $line | awk -F'^' '{print $2}');         sed -i "/$(echo $srch)/ s/$/^$(echo $rep)/" tmp.1; done 

Thanks!

like image 813
user1601716 Avatar asked Oct 03 '12 18:10

user1601716


People also ask

Does sed work in Python?

Description. pythonsed is a full and working Python implementation of sed.

Can you pipe to sed?

In Linux, pipes can help us to direct stdout to stdin. Therefore, we can first use the echo command to output the text to stdout and then pipe to the sed command.

How do you sed a specific line?

Just add the line number before: sed '<line number>s/<search pattern>/<replacement string>/ . Note I use . bak after the -i flag. This will perform the change in file itself but also will create a file.

What is I flag in sed?

In sed , you can end a command with the flag "/i" (for example, see this other question). This seems to say "more sed commands coming," or something like that, so you can split sed commands in a script.


1 Answers

Using re.sub():

newstring = re.sub('(Banana)', r'\1Toothpaste', oldstring) 

This catches one group (between first parentheses), and replaces it by ITSELF (the \number part) followed by a desired suffix. It is needed to use r'' (raw string) so that the escape is correctly interpreted.

like image 158
heltonbiker Avatar answered Oct 02 '22 00:10

heltonbiker