Friday, 20 December 2024

sed on FreeBSD file listing

sed can be used to modify a FreeBSD file listing with regular expressions, allowing you to convert an ls into a csv, for example.

Given a file listing like:

-rwxr-xr-x   1 Andrew.Potts  wheel   7417965 Apr 12  2023 Yoi.MOV

-rwxr-xr-x   1 Andrew.Potts  wheel  13536345 Apr 12  2023 Yondan Hands.mp4

-rwxr-xr-x   1 Andrew.Potts  wheel  11488336 Apr 12  2023 Zuki.mp4

You can create and test the regular expressions on Sed Tester: https://sed.js.org/

Note however, early versions of FreeBSD don't support characters like \s, \S or \d.
Instea you must use commands like [:alpha:]

ls -la | sed -E 's/^([-drwx\+]*)[[:space:]]+([0-9]+)[[:space:]]+([[:alpha:].]+)[[:space:]]+([[:alpha:]]+)[[:space:]]+([[:digit:]]+)[[:space:]]+([[:alpha:]]+[[:space:]]+[[:digit:]]+[[:space:]]+[[:digit:]]+)[[:space:]]+(.+)$/\7,\5,\6/p'



's/\(.* [A-Za-z]* [0-9]*\) \([0-9]*\) \([a-z|A-Z]* [0-9]* [0-9]*:[0-9]*\) \(.*\)/\4,\2,\3/'

 ls -la | sed -E 's/^([-drwx\+]*)[[:space:]]+([0-9]+)[[:space:]]+([[:alpha:].]+)(.+)$/\3/p'

Capture 

([-rwx]*)\s+(\d+)\s+(\S+)\s+(\S+)\s+(\d+)\s+(\w+\s+\d+\s+\d+)\s+(.+)$

--regexp-extended --expression='s/^([-rwx]*)\s+([0-9]+)\s+(\S+)\s+(\S+)\s+([0-9]+)\s+(\S+\s+[0-9]+\s+[0-9]+)\s+(.+)$/\5,\6,\7/'