Lets say I want to capitalise the first word following the word jumped. Example below

Original text:

the cow jumped over the moon

Amended text

the cow jumped OVER the moon

I have tried awk and sed but cant seem to get it right.

Thanks in advance

  • 1
    What did you try with awk?
    – vanadium
    May 17 at 10:15
  • what if "jumped" is the last word in a line, should the first word of the next line be upper case?
    – pLumo
    May 17 at 10:48

3 Answers 3


With sed:

  • Enable extended regular expressions with the option -E.

  • Then capture the specific word in a group () with the space after it \s so your example specific word will look like this (jumped\s).

  • Then capture the word after it in a second group like this (\w+).

  • Then call the two groups \1 and \2 and capitalize all letters in group number 2 with \U like this \1\U\2

  • Then put the whole thing in 's/string1/string2/g' where s means search for string1 and when found, change it to string2 and g means global search i.e. search and substitute on all lines.

  • Then use it on text from a pipe like so:

    echo "the cow jumped over the moon" | sed -E 's/(jumped\s)(\w+)/\1\U\2/g'
  • Or use it on text from a file like so:

    sed -E 's/(jumped\s)(\w+)/\1\U\2/g' file
  • And the result from your example will look like this:

    the cow jumped OVER the moon

Loop the words in a row, and if the word before the current word ($(i-1)) is jumped, overwrite the current word ( $i) with toupper($i).

awk '{for (i=1; i<=NF; i++) { if ($(i-1)=="jumped") $i=toupper($i); }}1'

You could also change the record separator to space to avoid the loop:

awk 'BEGIN{RS=ORS=" "} l=="jumped"{$0=toupper($0)} {l=$0}1'

Depending on how you want to use the output, you could do something like this (an idea that you could modify for your needs):

a="the cow jumped over the moon"
echo $a | awk '{
for(i = 1; i <= NF; i++){
if($(i-1)~/jumped/){printf toupper($i)}
else{printf $i}
printf " "}

This will output: the cow jumped OVER the moon

This assumes that the word to be modified is on the same line as "jumped".


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.