How to pipe output from cat to cut

23,739

Solution 1

The default field delimiter for cut is a tab. Since your file has a space instead, you need to specify the delimiter:

-d ' '

And you really don't need to use cat or a pipe at all. Just read the file directly.

cut -f 1 -d ' ' /proc/uptime

Solution 2

cat /proc/uptime | cut -f1 -d' '

is correct

< /proc/uptime  cut -f1 -d' '

is correct and more efficient as it reads from /proc/uptime directly without creating a pipe (not that it matters here much).

It's generally advisable to use the second form on forums, or else you'll get purists coming after you shouting "useless use of cat".


cut -f1 -d' ' < cat /proc/uptime

is wrong. It's the same as

cut -f1 -d' ' /proc/uptime < cat

If you're in bash, you can also use <():

cut -f1 -d' ' < <(cat /proc/uptime)

This creates an anonymous named pipe for reading and the output of cat /proc/uptime will be piped into it. But again—useless use of cat.

Other than that, cut can also take a file argument so all the redirect versions will also work without the < (it shouldn't matter efficiency-wise):

cut -f1 -d' '/proc/uptime

Or with the <() pipe:

cut -f1 -d' ' <(cat /proc/uptime)
Share:
23,739

Related videos on Youtube

brenguy
Author by

brenguy

Updated on September 18, 2022

Comments

  • brenguy
    brenguy over 1 year

    I want to cat /proc/uptime into cut -f1 in a Bash script.

    I've tried;

    cat /proc/uptime | cut -f1
    cat /proc/uptime > cut -f1
    cut -f1 < cat /proc/uptime
    

    Do I need to use echo or something else to make this happen?

    • Admin
      Admin almost 9 years
      What are you trying to do, exactly? It's difficult to tell from that one-liner. The first one is correct but unnecessary as cut takes [FILE] as command-line parameter.
    • Admin
      Admin almost 9 years
      Sorry I am trying to cat the results of uptime in seconds. I only want the first field of output from /proc/uptime
    • Admin
      Admin almost 9 years
      Figured it out! I needed to specify the delimiter.... I thought that was set default to space. My one-liner looks like this now: cat /proc/uptime | cut -d' ' -f1
    • Admin
      Admin almost 9 years
      It made sense after I fixed your markdown. :) You can also do this with Awk, and is IMO, easier to remember. awk '{ print $1 }' /proc/uptime
    • Admin
      Admin almost 9 years
  • Aaron Copley
    Aaron Copley almost 9 years
    I am going to create a shell. You'll have to opt-in of course, but every pipe results in a donation to charity from $USER's bank account.
  • Admin
    Admin almost 9 years
    Bonus: How would I then do a if [ output -lt specified time] then do this in bash...
  • Amitav Pajni
    Amitav Pajni almost 9 years
    @brenguy That would be an entirely separate question. Here we prefer distinct questions to be asked separately, as this is not a forum and not intended to be.