BASH: string manipulation
Hi, I am trying to figure out how to isolate certain parts of string.
In a given file (test.txt) I have some lines: blah [Need this phrase] bblah blah ya [Need this phrase as well] Is there a way for me to extract only what is in the square brackets? Even if the text goes to the next line? The extracted phrase should be saved as a variable. Is there any way to do this with the sed command? Thank you! |
Hello,
You would have to use sed for this. Look at the following: Code:
sed -e 's/.*\[\([^]]*\)\].*/\1/g' Code:
echo "blah [Need this phrase] bblah" | sed -e 's/.*\[\([^]]*\)\].*/\1/g' Cheers, Josh |
Great!
Thanks for the quick reply!!! When I run this: sed -e 's/.*\[\([^]]*\)\].*/\1/g' test.txt and test.txt is: blah [Need this phrase] bblah blah ya [Need this phrase as well] It outputs: Need this phrase blah ya [Need this phrase as well] Is there any way I can get it to keep reading lines? When the desired string begins on one line and continues on another line how could I get it keep reading through to the next line until it finds the end ]. Thanks again in advance |
How about:
Code:
sed -r ':a /]/! N;ta;s/.*\[(.*)\].*/\1/' file |
Code:
$ ruby -0777 -ne '$_.split("]").each{|x| puts "#{x.split("[")[-1]}" if x[/\[/] }' file |
So still learning from the master <bow> to kurumi :)
Now that i have seen what 0777 can do: Code:
ruby -0777 -ne 'puts $_.scan(/\[([^\]]+)/)' file |
Using GNU awk
Code:
echo ' Code:
awk '/./{gsub(/\n/," ");print}' RS='[^]]*[[]\n?|\n?][^[]*' |
small correction
Quote:
This works as long as there are no multiple patterns on the same line to keep: Code:
sed -r ':a /]/! N;s/.*\[(.*)\].*/\1/;Ta' file |
Cheers crts ... still getting my sedfu together :) although I noticed with Kenhelm's example this doesn't get all the necessary ones :(
|
Quote:
Quote:
Code:
sed -nr ':a /\[[^]]*$/ {N;ba}; s/[^[]*\[([^]]*)\][^[]*/\1/pg; ' file |
All times are GMT -5. The time now is 04:30 PM. |