Sed inside an awk statement

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 hours@8.25 Employee : Connor 25 hours@8.00 Employee : Dylan 30 hours@9.00 

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 
2

3 Answers

$ cat roster.txt foo : bar@baz.123 Employee : Kiara 20 hours@8.25 Employee : Connor 25 hours@8.00 Employee : Dylan 30 hours@9.00 $ awk 'BEGIN{FS=OFS=" : "} $1=="Employee"{gsub(/ /,"_",$2); gsub(/@/,"at",$2); gsub(/\./,"dot",$2)} 1' roster.txt foo : bar@baz.123 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
4

I'd write:

sed '/^Employee :/ {s/@/at/; s/\./dot/; s/ /_/3g}' <<END Employee : Kiara 20 hours@8.25 Employee : Connor 25 hours@8.00 Employee : Dylan 30 hours@9.00 Foo : bar END 
Employee : Kiara_20_hoursat8dot25 Employee : Connor_25_hoursat8dot00 Employee : Dylan_30_hoursat9dot00 Foo : bar 

Requires GNU sed for the 3g modifier of the s command

4

You really do not need to use both tools, either will do everything you need.

sed solution:

 sed -i -e 's/^Employee : \([^ ]*\) \([0-9]*\) hours@\([0-9]\)\.\([0-9]*\)/Employee : \1_\2_hoursat\3dot\4/' roster.txt 

Edit after comment:

If you want a very generic replacement using only sed that works on your sample:

sed -i -e 's/\([^:]\) \([^:]\)/\1_\2/g' -e 's/@/at/g' -e 's/\./dot/g' roster.txt 
2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like