sebastiano.tronto.net

Source files and build scripts for my personal website
git clone https://git.tronto.net/sebastiano.tronto.net
Download | Log | Files | Refs | README

expand-unexpand.md (1925B)


      1 # UNIX text filters, part 2.5 of 3: expand and unexpand
      2 
      3 *This post is part of a [series](../../series)*
      4 
      5 Last week some guys at my company gave a little lecture on
      6 [rust](https://www.rust-lang.org). They gave us some practical exercises,
      7 with some partially-written source files to complete. Unfortunately, the
      8 source files used spaces instead of TABs!
      9 
     10 Luckily I knew how to use `unexpand` to fix this. And in case you
     11 are shaking your head in horror because you prefer spaces, worry
     12 not: `expand` can save you when you face the opposite problem.
     13 
     14 ## expand
     15 
     16 The `expand` command converts tabs into spaces. By default every
     17 TAB character *at the beginning of each line* is replaced by 8
     18 spaces, but you can choose a different width with the `-t` option.
     19 You can also choose to expand *all* TABs, not just the leading ones,
     20 using the `-a` option. For example:
     21 
     22 ```
     23 $ echo '	hello	world?' | expand -t 3
     24    hello	world?
     25 ```
     26 
     27 As you can see, the TAB in the middle of the line is preserved.
     28 Well I guess you can't really see it. Also, I am pretty sure the
     29 markdown-to-html converter I use turns tabs into spaces anyway.
     30 This example is a trainwreck, let's move on.
     31 
     32 ## unexpand
     33 
     34 Unsurprisingly, `unexpand` does just the opposite of `expand`: it
     35 converts groups of leading spaces into TABs. So the command I used
     36 to "fix" the source files for the rust exercises was:
     37 
     38 ```
     39 $ unexpand -t 4 main.rs
     40 ```
     41 
     42 or to be more precise, since I wanted to replace the original file:
     43 
     44 ```
     45 $ unexpand -t 4 main.rs > main.rs.2 && mv main.rs.2 main.rs
     46 ```
     47 
     48 or to be even more precise, since I wanted to do this for multiple files:
     49 
     50 ```
     51 $ for f in *.rs; do unexpand $f > $f.2 && mv $f.2 $f; done
     52 ```
     53 
     54 ## Quirks
     55 
     56 For some reason, the OpenBSD version of `unexpand` does not allow
     57 using the `-t` option. So if I had brought my OpenBSD laptop at the
     58 rust lecture I would have been stuck with spaces :(
     59 
     60 *Next in the series: [fold](../2024-05-31-fold)*