0

My input file is

cat random.txt

hello my name is hello

When I use egrep '^hello|hello$ random.txt

results are hello my name is hello

How would I modify the command to instead output something like this

hello my name is

or

my name is hello

basically removing the same word if it starts at the beginning or end of the line if both words were to be on the same line?

  • 1
    You need more examples of what you want. Your `grep` command looks for `hello` at the beginning or end of a line, but will print the whole line. But you apparently want some processing after that, or some indication whether the "hello at beginning" or "hello at end" was triggered. What if a line says `hello my name is Bob and I say hello whenever anybody says hello to me, hello" What do you want the output to be? – Dave M. Jun 08 '20 at 01:35

2 Answers2

0

You can combine it with awk like this:

egrep '^hello|hello$' random.txt | awk '{$1=""; print $0}'

That means, the results from egrep are sent to awk. awk splits each word, resets the first word represented by $1 to empty string and prints out rest of the line.

zedfoxus
  • 35,121
  • 5
  • 64
  • 63
0

Do you have to use grep? You can achieve this effect with sed:

sed -e 's/hello/PLACEHOLDER/g' -e 's/PLACEHOLDER/hello/1' -e 's/PLACEHOLDER//1' random.txt

Which returns:

hello my name is 

To clarify what we did:

  • First we replace all matches of "hello" with "PLACEHOLDER"
  • Then we replace the first match of "PLACEHOLDER" with hello
  • Finally we replace the remaing matches of "PLACEHOLDER" with an empty string

This solution is based in this answer for a question regarding sed.

Telmo Trooper
  • 4,993
  • 1
  • 30
  • 35