21

I have a file str.txt with the following sample records.

31,2713810299,1,11-Aug-15 19:52:10
32,2713810833,1,11-Aug-15 21:36:18

Now I want to print output with awk as below.

cat str.txt|awk -F, '{print substr("$4",1,9)}' -

The output should be:

'11-Aug-15' 
'11-Aug-15' 
0

4 Answers 4

33

a single quote would be \x27

awk -F, '{print "\x27"substr($4,1,9)"\x27" }'
2
7

POSIXly:

awk -F'[ ,]' -v q="'" '{print q$4q}' <file
1
  • brilliant and elegant
    – hmontoliu
    Commented Oct 25, 2023 at 7:09
2

A slightly different approach, for POSIX Awk:

awk -F'[, ]' '{printf "\047%s\047\n", $4}' file
'11-Aug-15'
'11-Aug-15'
0

You could use awk command like this:

cat str.txt|awk -F, '{print substr($4,1,9)}' -

To get following output:

11-Aug-15
11-Aug-15

If single quotes requires at the start and end of lines then:

cat str.txt|awk -F, '{printf "\047%s\047\n",substr($4,1,9)}' -

To get following output:

'11-Aug-15'
'11-Aug-15'
2
  • No single quotes are printed, which the question specifies...
    – jasonwryan
    Commented Oct 16, 2015 at 2:01
  • @jasonwryan: Please check answer updated as per requirement.
    – snoop
    Commented Oct 16, 2015 at 4:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .