Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed inside an awk statement

Tags:

sed

awk

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
like image 369
cbrad97 Avatar asked Aug 08 '17 14:08

cbrad97


People also ask

Can I use sed in awk?

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.

What is grep awk sed?

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.

What is GSUB in awk?

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.


1 Answers

$ 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 separator
  • gsub(/ /,"_",$2) replace all spaces with _ only for second field
  • Similarly other substitutions as required
  • 1 at end of command is idiomatic way to print the line, includes any changes made
  • See also awk save modifications in place
like image 198
Sundeep Avatar answered Nov 09 '22 19:11

Sundeep