DomainsFeatured
DomainsFeatured

Reputation: 1506

How Can I Perform Awk Commands Only On Certain Fields

I have CSV columns that I'm working with:

info,example-string,super-example-string,otherinfo

I would like to get:

example-string super example string

Right now, I'm running the following command:

awk -F ',' '{print $3}' | sed "s/-//g"

But, then I have to paste the lines together to combine $2 and $3.

Is there anyway to do something like this?

awk -F ',' '{print $2" "$3}' | sed "s/-//g"

Except, where the sed command is only performed on $3 and $2 stays in place? I'm just concerned later on if the lines don't match up, the data could be misaligned.

Please note: I need to keep the pipe for the SED command. I just used a simple example but I end up running a lot of commands after that as well.

Upvotes: 1

Views: 796

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133528

Though best solution will be either use a single sed or use single awk. Since you have requested to use awk and sed solution so providing this. Also considering your actual data will be same as shown sample Input_file.

awk -F, '{print $2,$3}' Input_file | sed 's/\([^ ]*\)\([^-]*\)-\([^-]*\)-\([^-]*\)/\1 \2 \3 \4/'

Output will be as follows.

example-string  super example string

Upvotes: 1

John1024
John1024

Reputation: 113844

Try:

$ awk -F, '{gsub(/-/," ",$3); print $2,$3}' file
example-string super example string

How it works

  1. -F,

    This tells awk to use a comma as the field separator.

  2. gsub(/-/," ",$3)

    This replaces all - in field 3 with spaces.

  3. print $2,$3

    This prints fields 2 and 3.

Examples using pipelines

$ echo 'info,example-string,super-example-string,otherinfo' | awk -F, '{gsub(/-/," ",$3); print $2,$3}'
example-string super example string

In a pipeline with sed:

$ echo 'info,example-string,super-example-string,otherinfo' | awk -F, '{gsub(/-/," ",$3); print $2,$3}' | sed 's/string/String/g'
example-String super example String

Upvotes: 4

Related Questions