The POSIX tool for scripted edits of a file (rather than printing the modified contents to standard out) is ex
.
printf '%s\n' 'g/^[^C]*C[^C]*$/d' x | ex file.txt
Of course you can use sed -i
if your version of Sed supports it, just be aware that's not portable if you're writing a script that's intended to run on different types of systems.
David Foerster asked in the comments:
Is there a reason why you're using printf
and not echo
or something like ex -c COMMAND
?
Answer: Yes.
For printf
vs. echo
it's a question of portability; see Why is printf better than echo? And it's also easier to intersperse newlines between commands using printf
.
For printf ... | ex
vs. ex -c ...
, it's a question of error handling. For this specific command it would not matter, but in general it does; for example, try putting
ex -c '%s/this pattern is not in the file/replacement text/g | x' filename
in a script. Contrast with the following:
printf '%s\n' '%s/no matching lines/replacement/g' x | ex file
The first will hang and await input; the second will exit when EOF is received by the ex
command, so the script will continue. There are alternative workarounds, such as s///e
, but they are not specified by POSIX. I prefer using the portable form, which is shown above.
For the g
command, there must be a newline at the end, and I prefer using printf
to wrap the commands rather than embedding a newline in single quotes.
awk
field separator ! – Valentin B. May 02 '17 at 09:24awk 'BEGIN { print "FS={" FS"}","OFS={" OFS "}";} {printf "%d fields : ",NF; for (i=1;i<=NF;i++) {printf "{" $i "} ";}; print "" }'
and feed it some lines, some having multiple spces, and others begininng with space(s)) – Olivier Dulac May 02 '17 at 16:18