0

Example of file.txt:

/map/1.0.0/cd/base/4/23/82.png 200
/map/1.0.0/cd/base/2/48/154.png?fefsfes 200
/map/1.0.0/cd/base/3/45/433.png?gtdrdrg 200

I need to delete this:

.png
.png?fefsfes
.png?gtdrdrg

I use this

$ cat file.txt | awk '{ print $1","$2}'

to get result:

/map/1.0.0/cd/base/4/23/82.png,200
/map/1.0.0/cd/base/2/48/154.png?fefsfes,200
/map/1.0.0/cd/base/3/45/433.png?gtdrdrg,200

Can I somehow fetch column with awk '{ print $1}' and delete everything after last number?

Wanted result:

/map/1.0.0/cd/base/4/23/82,200
/map/1.0.0/cd/base/2/48/154,200
/map/1.0.0/cd/base/3/45/433,200
5
  • 1
    You mean something like this sed 's/\.png.*\ /,/' file.txt? Oct 25 '16 at 20:04
  • How can I include that in this: $ cat file.txt | awk '{ print $1","$2}' Oct 25 '16 at 20:08
  • It replaces all of that in one command (in theory). Oct 25 '16 at 20:10
  • But if I put that as: $ cat file.txt | awk '{ print $1","$2}' | sed 's/\.png.*\ /,/' nothing happens Oct 25 '16 at 20:10
  • There is no need for cat or awk, just the sed command will handle everything. $ sed 's/\.png.*\ /,/' file.txt Oct 25 '16 at 20:12
2

If you want to preserve the essence of your awk command, then you can simply sub away the unwanted trailing portion of $1

awk '{sub(/\.png.*$/,"",$1); print $1","$2}' file

or (perhaps more awkishly)

awk '{sub(/\.png.*$/,"",$1)}1' OFS=, file
0

You can try below awk solution -

awk 'BEGIN{FS=".png| "} {print $1,$NF}' kk.txt |tr ' ' ','

using multiple field seperator.

1
  • Outside the awk tr is working fine to remove the space with comma but inside the awk it is throwing below error - awk 'BEGIN{FS=".png| "} {print $1,$NF|tr ' ' ','}' kk.txt awk: line 2: missing } near end of file awk 'BEGIN{FS=".png| "} {print $1,$NF|"tr ' ' ','"}' kk.txt awk: line 1: runaway string constant "tr ... Oct 29 '16 at 20:33

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.