0

I have a file with multiple lines of text similar to:

foo
1
2
3
bar
fool
1
2
3
bar
food
1
2
3
bar

So far the following gives me a closer answer:

sed -n '/foo/,/bar/ p' file.txt | sed -e '$d'

...but it fails by introducing duplicates if it encounters words like "food" or "fool". I want to make the code above do a whole word match only (i.e. grep -w), but inserting the \b switch doesn't seem to work:

sed -n '/foo/\b,/bar/ p' file.txt | sed -e '$d'

I would like to print anything after "foo" (including the first foo) up until "bar", but matching only "foo", and not "foo1".

  • 1
    See: [The Stack Overflow Regular Expressions FAQ](http://stackoverflow.com/a/22944075/3776858) – Cyrus Aug 09 '16 at 05:28

2 Answers2

2

Use the Regex tokens ^ and $ to indicate the start and end of a line respectively:

sed -n '/^foo$/,/^bar$/ p' file.txt
heemayl
  • 32,535
  • 3
  • 52
  • 57
  • ...but is it possible to expand this to deal with non-word constituent characters preceding or following like "Name=foo, " and count as a positive match? @heemayl – supertonic09 Aug 09 '16 at 14:28
  • @supertonic09 yes, possible..check if `sed -n '/^[^[:alpha:]]*foo[^[:alpha:]]*/,/^[^[:alpha:]]*bar[^[:alpha:]]*/ p' file.txt` is working for you.. – heemayl Aug 09 '16 at 14:30
  • I ended up taking a different approach, and decided to split the logic into two parts like this: `foo_match=$(grep -m 1 -w foo file.txt);` `sed -n "/$foo_match/,/bar/ p" file.txt | sed -e '$d'` But off course, the above implementation works for me @heemayl, because I'm expecting the final application to contain a more complex string than just `foo`, making it unique when passed on to `sed`. – supertonic09 Aug 09 '16 at 15:54
0
sed -n '/\<foo\>/,/\<bar\>/ p' file.txt

Or may be this if foo and bar have to be first word of any line.

sed -n '/^\<foo\>/,/^\<bar\>/ p' file
P....
  • 10,757
  • 1
  • 19
  • 38