I'd like to perform a series of sed commands on lines of a file roster.txt only beginning with a keyword. For example:
Employee : Kiara 20 [email protected]
Employee : Connor 25 [email protected]
Employee : Dylan 30 [email protected]
Becomes:
Employee : Kiara_20_hoursat8dot25
Employee : Connor_25_hoursat8dot00
Employee : Dylan_30_hoursat9dot00
I know the sed commands to make the changes I just wanted a way to peform them on lines starting with "employee". Maybe
awk '$1 == "Employee" {sed -i -e 's/\./dot/g' roster.txt}' roster.txt
You can also write an awk program using an editor, and then save it as a special scripting file, e.g. sed performs basic text transformations on an input stream (a file or input from a pipeline) in a single pass through the stream, so it is very efficient.
Grep, sed, and AWK are all standard Linux tools that are able to process text. Each of these tools can read text files line-by-line and use regular expressions to perform operations on specific parts of the file. However, each tool differs in complexity and what can be accomplished.
gsub stands for global substitution. It replaces every occurrence of regex with the given string (sub). The third parameter is optional. If it is omitted, then $0 is used.
$ cat roster.txt
foo : [email protected]
Employee : Kiara 20 [email protected]
Employee : Connor 25 [email protected]
Employee : Dylan 30 [email protected]
$ awk 'BEGIN{FS=OFS=" : "} $1=="Employee"{gsub(/ /,"_",$2); gsub(/@/,"at",$2); gsub(/\./,"dot",$2)} 1' roster.txt
foo : [email protected]
Employee : Kiara_20_hoursat8dot25
Employee : Connor_25_hoursat8dot00
Employee : Dylan_30_hoursat9dot00
awk
supports substitution commands as well - sub
to replace first occurrence and gsub
to replace all occurrences. Also allows to change only specific field
BEGIN{FS=OFS=" : "}
use :
as input/output field separatorgsub(/ /,"_",$2)
replace all spaces with _
only for second field1
at end of command is idiomatic way to print the line, includes any changes madeIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With