In using sed
, I often create rather complicated and intricate regexes that I need to match twice in a file. Is there a way for me to save this regex and just reference it twice?
Maybe something that looks like this?
sed ' complicated_regex=/^(([a-f0-9]{32})+([a-zA-Z0-9=]{{$i}})?)+$/
s/complicated_regex:complicated_regex/simple-output/
' my_file
Update: An answer has presented the solution of using a bash variable. This doesn't work. Given a test.txt
.
#test.txt
foo bar
bar foo
And the script
#!/bin/bash
VALUE='foo \([a-z]\+\)'
sed 's/"${VALUE}"/foo happy \1/' test.txt
This should produce the output
foo happy bar
bar foo
But instead I get the error
sed: -e expression #1, char 24: invalid reference \1 on `s' command's RHS
perl -pe 's/^(([a-f0-9]{32})+([a-zA-Z0-9=]{{$i}})?)+:\1$/simple_output/' my_file
– glenn jackman Sep 21 '11 at 20:10sed 's/'"${VALUE}"'/foo happy \1/' test.txt
– Peter.O Sep 22 '11 at 4:32