3
I'm trying to use sed to search for a certain 'primary' pattern that may exist on several lines, with each primary pattern followed by an --unknown-- number of 'secondary' patterns.
The lines containing the pattern start with: test(header_name)
On that same line is an arbitrary number of strings that come after it.
I want to move those strings over to their own lines so that they each are preceded by their own test(header_name)
.
e.g. Original file (mytest.txt):
apples
test("Type1", "hat", "cat", "dog", "house");
bananas
oranges
test("Type2", "brown", "red", "green", "yellow", "purple", "orange");
I want it to become:
apples
test("Type1", "hat");
test("Type1", "cat");
test("Type1", "dog");
test("Type1", "house");
bananas
oranges
test("Type2", "brown");
test("Type2", "red");
test("Type2", "green");
test("Type2", "yellow");
test("Type2", "purple");
test("Type2", "orange");
This would be easy to do if we knew the number of strings per line, but in this case it is not fixed.
The clumsy way would be to do this:
while ( a line exists that starts with 'test' and contains more than two args)
do
Keep the first and second args
Move the rest of that line to a new line and add 'test(header)' to the front
done
But this is time consuming, especially if there are hundreds of strings.
Any ideas?
Does the answer have to specifically be for SED, or would you accept other possible text manipulation answers (perl, awk, etc.)? I personally think the loop is going to be the best way, but those other tools may work better and someone who is more familiar with them may provide a more time efficient answer should they be available. – Matrix Mole – 2011-07-05T17:33:24.477
I prefer sed but perl is ok too. I've been designing a tool for multiple platforms and I have been getting people to use GNU sed. Thanks – Dan – 2011-07-05T17:47:58.883