0
$ stat -c "%Y#%n#%y" *  | awk -F'#' "BEGIN {OFS=\"|\"} NR==1,NR==3 {print \$2 \$3}"
directory1/Blum2017-12-22 22:33:38.644178442 -0500
dir2/Ciolli2017-12-22 21:53:51.769368496 -0500
Dar2017-12-06 13:29:37.698296879 -0500

I try to set up input and output field separators.

  • I use # as input separator, but a filename can contains #. Is there a better choice? I don't know if stat can separate the output pathnames by /null as find does and if awk can accept input field separator \null.

  • why does my setup of OFS to | not work?

Thanks.

  • 1
    (1) it depends - what are you trying to do, exactly? (2) because \$2 \$3 is a string concatenation: try \$2,\$3 – steeldriver Jun 13 '18 at 22:56
  • Thanks. (1) I want to make sure the three pieces of information provided by stat are recognzed by awk as separate fields. – Tim Jun 13 '18 at 23:27
  • It seems the use of null is problematic: see this insightful answer. – simlev Jun 14 '18 at 15:47
1
stat -c "%Y/%n/%y" * | awk -F'/' 'NR==1,NR==3 {print $2"|"$3}'

Or:

stat -c "%Y/%n/%y" * | awk -F'/' 'BEGIN {OFS="|"} NR==1,NR==3 {print $2,$3}'

Explanation:

Instead of #, you might want to use / (the directory separator), since it can not be part of a filename.

The input awk field separator needs to be set accordingly: -F'/'.

As already pointed out in a comment by @steeldriver, you have two ways of choosing an output field separator.

  1. Use string concatenation: print $2"|"$3.
  2. Define OFS="|" and then print $2,$3.

I chose single quotes ' over double quotes " which reduces the need of escaping in this case.

Update:

Since the question now specifies that the stat output may contain the directory separator, / would not be a wise choice for the record separator. The only other character that I know of which is not allowed in filenames is NUL, but its use is problematic at least in this case. My suggestion would be to make up an awkward string that is very unlikely (although allowed) to be found as part of a filename. Accidentally, \x0 (which is a representation of NUL) could be a good choice:

stat -c "%Y\x0%n\x0%y" * | awk -F\x0 'BEGIN {OFS="|"} NR==1,NR==3 {print $2"|"$3}'
  • Thanks. The output of stat can be pathnames containing /, because there can be subdirectories in the expansion of *. – Tim Jun 14 '18 at 15:24
  • @Tim Your best bet is to use the NUL character then! – simlev Jun 14 '18 at 15:27
  • How shall I specify NUL to stat and awk? – Tim Jun 14 '18 at 15:28
  • I don't think it will work. You can specify a very awkward string that is unlikely to be found in filenames, such as #°°#. – simlev Jun 14 '18 at 15:40

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.