1

Fist I am trying to print a file with the word 'Guess' in it and change the word fall to bar.

This what I have tried:

sed -n -e '/Guess/p' -e 's/Fall/bar/' data.txt

The commands work fine alone however, together only the first part is working.

JUSHJUSH
  • 367
  • 1
  • 11
Noel S
  • 19
  • 3

1 Answers1

0

To print line containing 'Guest' and change word 'Fall' in that line,

I would try experimenting with this command>

cat data.txt | sed -n '/Guest/{ s/Fall/bar/p }'

However, this print nothing, if the line with 'Guest' does not contain the word 'Fall'. (Both scenarios - Guest + Fall are required)

If you want to print line containing 'Guest' no matter if substitution finds a word 'Fall', I suggest trying:

cat data.txt | sed -n '/Guest/ { s/Fall/bar/;p }'
  • You will want to avoid the [useless `cat`.](/questions/11710552/useless-use-of-cat) – tripleee Dec 19 '19 at 13:43
  • is it dangerous? (if we think of scenario when one don't mind spawning an extra process) –  Dec 19 '19 at 14:06
  • No, just wasteful. The linked answer has an answer by me with some elaboration and another which attempts to quantify the additional overhead. – tripleee Dec 19 '19 at 14:09
  • I understand the concerns from hardware usage point of view. However, the division into two separate commands, each doing own thing "good" feels better for me. (even if it means more hardware usage). Meaning why should every command have it's own function to read files or '<' operator be used if we have pipes and a command for reading files. (and rest of commands could work simply with input given, not bothering with reading files on it's own). For simplicity and clarity, I prefer to use this structure of program. –  Dec 19 '19 at 14:14