clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

Print a bash command output into a file

Filed under: System— Tagged with: bash

This post shows how to redirect an output of a command, or static text, into a file.

The redirection operator > or >>

Print string into a file:

$ touch foo.txt
$ echo "hello" > foo.txt

Or append with the double redirection operator:

$ echo "hello" >> foo.txt

Append command output into a file:

$ ls >> foo.txt

cat it, to see if it worked:

$ cat foo.txt

Thinking of a real world example, one that comes to mind is to add fish to your available shells:

$ which fish >> /etc/shells

The tee command

You can also pipe into the tee command:

$ which fish | tee ./foo.txt

Use the -a flag to append:

$ which fish | tee -a foo.txt

The paste command

This command will output file names separates by a comma:

$ ls -1 | paste -sd "," -
foo.txt,bar.txt,baz.txt

It breaks down to:

-1
(The numeric digit one.) Force output to be one entry per line. This is the default when output is not to a terminal.
-s
Concatenate all of the lines of each separate input file in command line order. The newline character of every line except the last line in each input file is replaced with the tab character, unless otherwise specified by the -d option.
-d
Use one or more of the provided characters to replace the newline characters instead of the default tab.
-
The hyphen at the end means standard input.

Just change the comma to whatever you like:

$ ls -1 | paste -sd "\n" - > foo.txt

If you want to limit the results, globs can be used in normal fashion. This lists only jpg files:

$ ls -1 *.jpg | paste -sd "," - > jpegs.txt

Or jpgs and pngs:

$ ls -1 *.{jpg,png} | paste -sd "," - > bitmaps.txt

Make a CSV

A super primitive receipt management system. Name your receipts in this format:

yyyy-mm-dd,recipient,item,price,reference,.ext

An example file might look like this:

2014-01-25,DigitalOcean,10,server,165496-21,.pdf

Then print them out into a file:

$ ls -1 *.pdf | paste -sd "n" - > receipts-2015.csv

Then open it up in spreadsheet application of some sort.

Screenshot 2015-03-03 09.47.13
v

Comments would go here, but the commenting system isn’t ready yet, sorry. Tweet me @hiljaa if you want to make a correction etc.

  • © 2021 Antti Hiljá
  • About
  • Follow me in Twatter → @hiljaa
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!