Feel free to change the title as it does not match my question 100%
I have something like this in a file:
junk
long_ass_string "/I/want/this/$code/$name" long_ass_string
junkClarifying the example:
- The /I/want/this/ part is always the same
- $code and $name are dynamic and different for each string
- Inside long_ass_string there can be more /I/want/this/$code/$name strings and I would like to get all of them.
- The quotation marks (this => ") are present in every /I/want/this/$code/$name string.
So far I've tried...
grep -w "/I/want/this/*" file # outputs long_ass_stringgrep -o "/I/want/this/*" file # outputs /I/want/this/
Would like to avoid using the solution of getting only x extra characters before and/or after
42 Answers
I would go with grepping all strings and then sort it out with a second grep, e.g.:
grep -o '"[^"]*"' fileOutput:
"/I/want/this/$code/$name"Comment on your use of regular expressions
This expression /I/want/this/* matches /I/want/this and then zero or more slash characters, you probably meant: /I/want/this/.* which matches /I/want/this/ and zero or more characters.
if i understand you well you want to get ridd off the first $code and $name variable in each line. You can pipe your result to cut for that. Following your example:
grep "/I/want/this/" myfile.txt | cut -d '/' -f 1-4,7-with -d you define the delimiter ( the symbol / for instance) and with -f you indicate the field to grab.
In this case from delimiter 1 to 4 (/I/want/this/ ) and all the fields that come after the seventh delimiter (that is done with argument 7-)
Like this you takes away /$code/$name which are between 4th and 7th delimiter in all lines that match the defined regular expression.
echo "/I/want/this/NOT/THAT/and/everythingelse" | grep "/I/want/this/" | cut -d '/' -f 1-4,7-
/I/want/this/and/everythingelse 3