简体   繁体   中英

Invoking sed on grep results - linux shell script / text processing

What is the best way to invoke sed on grep results and save it to file? I wanna to change some lines in text file eg

Hi { Tom Mary Andy }

What { Eric John Ted }

Hi { Jerry Katy Mark }

So my problem is that i wanna add for example letter T. before all names that are included between brackets { } in lines that are "Hi" lines and overwrite file. Results should looks like that:

Hi { T.Tom T.Mary T.Andy }

What { Eric John Ted }

Hi { T.Jerry T.Katy T.Mark }

What do you think is the best solution / commands? I'm going to write shell script to do that. I know that i can grep that lines, later change it to array and concat but i dont think that is a nice solution :) Thanks for your help.

If you have:

Hi { Tom Mary Andy }
What { Eric John Ted }
Hi { Jerry Katy Mark }

and want to insert a 'T.' before each capital letter in lines beginning with 'Hi ', to obtain:

Hi { T.Tom T.Mary T.Andy }
What { Eric John Ted }
Hi { T.Jerry T.Katy T.Mark }

Then you can do that with sed alone. To edit the file in place, use the '-i' option for sed :

sed -i '/^Hi/s/\s\([A-Z]\)/ T.\1/g' filename.txt

note: to create a backup of the original file, use sed -i.bak

If you are using a mac or other OS where sed is provided without the '-i' option, then you can use:

sed '/^Hi/s/\s\([A-Z]\)/ T.\1/g' < filename.txt > newfilename.txt

with the results in newfilename.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM